其他分享
首页 > 其他分享> > SwiftUI 中 Hashable的作用?

SwiftUI 中 Hashable的作用?

作者:互联网

参考 https://www.jianshu.com/p/06c993c5ad89

只有遵循了Hashable 协议 才能被添加到 Set 中 或者用作 Dictionary 的 key 值。

比较结构体和类的不同,类必须要实现Hashable的协议方法

        struct Person:Hashable {
            var name: String
            var age: Int
        }

        let ming = Person(name: "ming", age: 10)
        let hong = Person(name: "hong", age: 11)

        var set: Set<Person> = []
        set.insert(ming)
        set.insert(hong)
        print(set)

        var dic:[Person: String] = [:]
        dic[ming] = ming.name
        dic[hong] = hong.name
        print(dic)
        
        
        let stu1 = Student(name: "东邪", age: 50)
        let stu2 = Student(name: "吸毒", age: 51)

        var set: Set<Student> = []
        set.insert(stu1)
        set.insert(stu2)
        print(set)

        var dict: [Student: String] = [:]
        dict[stu1] = stu1.name
        dict[stu2] = stu2.name
        print(dict)

        let stu3 = Student(name: "吸毒", age: 51)
        set.insert(stu3)
        dict[stu3] = stu3.name
        print("插入stu3 , name age同stu2 set结果= \(set)")
        print("插入stu3 , name age同stu2 dict结果= \(dict)")

        let stu4 = Student(name: "吸毒", age: 61)
        set.insert(stu4)
        dict[stu4] = stu4.name
        print("插入stu4 , name 同stu2 set结果= \(set)")
        print("插入stu4 , name 同stu2 dict结果= \(dict)")
        
        
        //假如我们对Person进行修改 , 年龄相同就当做同一个人?
class Student: Hashable {
    static func == (lhs: Student, rhs: Student) -> Bool {
        return lhs.name == rhs.name && lhs.age == rhs.age
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
        hasher.combine(age)
    }
    
    init(name: String,age: Int) {
        self.name = name
        self.age = age
    }
    
    var name: String
    var age: Int
}

 

标签:Hashable,set,name,age,SwiftUI,Student,var,dict,作用
来源: https://www.cnblogs.com/liuw-flexi/p/12625602.html