layraknahsas22314 layraknahsas22314 - 4 months ago 15
iOS Question

How to iterate over the values of a set in a specific order when the set is storing user-defined types in swift?

So from Swift's documentation, I know:


Swift’s Set type does not have a defined ordering. To iterate over the
values of a set in a specific order, use the sort() method, which
returns the set’s elements as an array sorted using the < operator.


I can understand how the sorting works for primitive data types while iterating but is there any way I can make it possible for user defined types? Suppose I have a class called Foo which conforms to the hashable protocol (I am not sure if it should be a requirement). Suppose Foo has two properties, ID and Username.

Is it doable? If yes, how can I make it work?

Answer

So, assume your Foo is something like this: (Swift 2 code)

class Foo: Hashable, CustomStringConvertible { // Hashable is mandatory to be a Swift Set element.
    var id: Int
    var username: String

    init(id: Int, username: String) {
        self.id = id
        self.username = username
    }

    //To conform to `Hashable`
    var hashValue: Int {
        return id.hashValue &+ username.hashValue
    }

    //useful for debugging
    var description: String {
        return "id: \(id), username: \(username)"
    }
}
//Also, to conform to `Hashable`
func == (lhs: Foo, rhs: Foo) -> Bool {
    return lhs.id == rhs.id && lhs.username == rhs.username
}

Make a sample Set:

let mySet: Set<Foo> = [
    Foo(id: 1, username: "Man"),
    Foo(id: 2, username: "Seven"),
    Foo(id: 3, username: "Jack"),
    Foo(id: 4, username: "Ace"),
    Foo(id: 5, username: "Taro"),
]

Iterating sorted by id:

for f in mySet.sort({$0.id < $1.id}) {
    print(f)
}

Outputs:

id: 1, username: Man
id: 2, username: Seven
id: 3, username: Jack
id: 4, username: Ace
id: 5, username: Taro

Iterating sorted by username:

for f in mySet.sort({$0.username < $1.username}) {
    print(f)
}

Outputs:

id: 4, username: Ace
id: 3, username: Jack
id: 1, username: Man
id: 2, username: Seven
id: 5, username: Taro

You can write similar code with any other Comparable properties. You can find many articles about sorting Arrays, Sets can be sorted in nearly the same way.

Comments