2

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.

2 Answers 2

1

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.

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

2 Comments

This is working. Thank you. Maybe another question, but in the same context, is this extendable to create groups for each letter, so that can be used in a tableview to use sections of alphabet?
@Caspert You're welcome. // This will help, sure, for example for filtering, but you will also need more - I think it would be better to ask a new question entirely, exposing your context, if you're struggling with this other task.
1

In Swift 3.0

you can do that simply like this.

peoples.sort(by: { (this: People, that: People) -> Bool in
    this. name < that. name
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.