1
class MyClass {
    var name: String?
    var address: String?

    init(name: String, address: String){
        self.name = name
        self.address = address
    }
}

let array = [MyClass(name: "John", address: "USA"), MyClass(name: "Smith", address: "UK"),MyClass(name: "Paul", address: "AUS"), MyClass(name: "Peter", address: "RSA")]

Now how can sort the array by name of MyClass object.

Eendje
  • 8,585
  • 1
  • 28
  • 31
Muzahid
  • 4,702
  • 2
  • 22
  • 36

3 Answers3

4
let sortedArray = array.sort { $0.name < $1.name }

This should do the trick.

Eendje
  • 8,585
  • 1
  • 28
  • 31
2
array.sortInPlace { $0.name < $1.name }
Ahmed Onawale
  • 3,852
  • 1
  • 16
  • 20
0

Correct way to implement this is to ensure your custom class conforms to the Comparable protocol and provides the implementations < and == operators. This will enable you to provide custom comparison and make it extensible.

Come up with an extension-

extension MyClass:Comparable{};


func ==(x: MyClass, y: MyClass) -> Bool {
    return x.name == y.name  //Add any additional conditions if needed
 } 

func <(x: MyClass, y: MyClass) -> Bool { 
   return x.name < y.name  //You can add any other conditions as well if applicable.
}

Now you can sort your array of object of this custom class like

let sorted = array.sort(<)
Shripada
  • 5,937
  • 1
  • 28
  • 30