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.

0

3 Answers 3

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

This should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

2
array.sortInPlace { $0.name < $1.name }

Comments

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(<)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.