美文网首页
Swift Hashable

Swift Hashable

作者: fordG | 来源:发表于2020-04-26 17:08 被阅读0次
import UIKit


let p = Person("123", id: 123)
Person.value = "123"
let b = Person("123", id: 123 )
let s = "123"


print(p.hashValue)
print(b.hashValue)
print(p == b)



class Person: Hashable {
    
    
    static var value: String?
    var name: String?
    var id: Int?
    
    init(_ name: String, id: Int){
        self.name = name
        self.id = id
    }
    
    func hash(into hasher: inout Hasher){
        //hasher.combine去帮我们实现了hashValue
        //内存地址来判断是否相等
        let add = address(o: self)
        hasher.combine(add)
        
        //通过自身的属性来判断是否相等
//        hasher.combine(name)
//        hasher.combine(id)
    }
    
}

func == (lhs: Person, rhs: Person) -> Bool {
    return lhs.hashValue == rhs.hashValue
}

func address<T: AnyObject>(o: T) -> String {
    return String.init(format: "%018p", unsafeBitCast(o, to: Int.self))
}

相关文章

网友评论

      本文标题:Swift Hashable

      本文链接:https://www.haomeiwen.com/subject/pmjjwhtx.html