Swift Hashable

Hashable

你可以使用你自定义的类型作为合集的值类型或者字典的键类型,只要让它们遵循Swift基础库的Hashable协议即可。遵循Hashable协议必须提供可获取的叫做hashValueInt属性。

因为Hashable协议遵循Equatable遵循的类型必须同时一个"等于"运算符(==)的实现Equtable协议需要任何遵循 == 的实现都具有等价关系。
举个栗子:

internal struct Mooshroom: Hashable {
    var name: String?
    var age: UInt?
    var hashValue: Int {
        get {
            var hashString = ""
            if let tName = self.name {
                hashString = tName + ";"
            }
            return hashString.hashValue
        }
    }
}
func == (lhs: Mooshroom, rhs: Mooshroom) -> Bool {
    return lhs.name == rhs.name && lhs.age == rhs.age
}
let moo1 = Mooshroom(name: "moo1", age: 24)
let moo2 = Mooshroom(name: "moo1", age: 24)

let arr1: Set = [moo1]
let arr2: Set = [moo2]

if arr1 == arr2 {
    print("arr1 == arr2")
} else {
    print("arr1 != arr2")
}
// 输出 arr1 == arr2

你可能感兴趣的:(Swift Hashable)