Caspert Caspert - 1 month ago 14
iOS Question

How to alphabetize an array of objects within Swift 3?

I try to list an array of objects in alphabetic order. I create this simple test, but doesn't know how to achieve this with an array of objects:

let names = ["Martin", "Nick", "Alex", "Ewa", "Barry", "Daniella", "Chris", "Robert", "Andrew"]

func alphabetizeArray(_ s1: String, _ s2: String) -> Bool {
return s1 < s2
}
let alphabeticNames = names.sorted(by: names)
print(reversedNames)


When I try this for an array of objects I came up with something like this:

func sorterForIDASC(this:People, that:People) -> Bool {
return this.name > that.name
}
peoples.sort(by: sorterForIDASC)


But this will give me an error of:
Binary operator '>' cannot be applied to two 'String?' operands


Anyone suggestions how to solve this. I would examine the names of each object that is from the type of
String
. I use Swift 3/Xcode8.

Answer

If you only need > then implementing > for your optional property is sufficient:

func >(lhs: People, rhs: People) -> Bool {
    if let left = lhs.name, let right = rhs.name {
        return left > right
    }
    return false
}

Now you can use > on an array of your objects:

let result = arrayOfObjects.sorted(by: >)

You could also have your object conform to Equatable and implement at least == and > for the optional property:

struct People: Equatable {
    var name: String?
}

func ==(lhs: People, rhs: People) -> Bool {
    if let left = lhs.name, let right = rhs.name {
        return left == right
    }
    return false
}

func >(lhs: People, rhs: People) -> Bool {
    if let left = lhs.name, let right = rhs.name {
        return left > right
    }
    return false
}

This opens even more possibilities.