参考 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 }