因此,假設你Foo
是這樣的: (斯威夫特2碼)
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
}
做一個樣品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"),
]
迭代通過id
排序:
for f in mySet.sort({$0.id < $1.id}) {
print(f)
}
輸出:
id: 1, username: Man
id: 2, username: Seven
id: 3, username: Jack
id: 4, username: Ace
id: 5, username: Taro
迭代的排序條件爲username
:
for f in mySet.sort({$0.username < $1.username}) {
print(f)
}
輸出:
id: 4, username: Ace
id: 3, username: Jack
id: 1, username: Man
id: 2, username: Seven
id: 5, username: Taro
您可以編寫類似的代碼與其他任何Comparable
性能。 你可以找到很多有關排序Array
s的文章,Set
s可以按幾乎相同的方式排序。
使您的課程符合「Comparable」協議。 – dan