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,815
  • 1
  • 29
  • 31
Muzahid
  • 5,072
  • 2
  • 24
  • 42

3 Answers3

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

This should do the trick.

Eendje
  • 8,815
  • 1
  • 29
  • 31
2
array.sortInPlace { $0.name < $1.name }
Ahmed Onawale
  • 3,992
  • 1
  • 17
  • 21
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
  • 6,296
  • 1
  • 30
  • 30