我来了,swift
界说
用于做值范例对比的协议。
实用范围
遵照Equatable的范例都可以使用==或是!=符号对比判定。这个范例包罗struct/class/enum
实现原理
任何遵照Equatable的范例,都须要实现方法static func ==(lhs: Self, rhs: Self) -> Bool在这个方法内按照指定的值和值间对比关系返回true或是false,外部表现为==或是!=的结果
struct Human: Equatable { var name: String var age = 5 static func == (lhs: Self, rhs: Self) -> Bool { return lhs.name == rhs.name }}let tom = Human(name: "tom", age: 5)let tim = Human(name: "tim", age: 6)tom == tim // falselet man1 = Human(name: "tom", age: 5)let man2 = Human(name: "tom", age: 6)man1 == man2 // trueHuman对Equatable方法界说为只判定name属性是否值雷同,即使age属性差别,man1==man2结果是true
在差别范例中的差别
- class遵照Equatable必须要实现static func ==(lhs: Self, rhs: Self) -> Bool方法。但是,struct遵照Equatable可以不消实现static func ==(lhs: Self, rhs: Self) -> Bool方法,默认将struct实例中全部属性对比并返回与结果
struct Dog: Equatable { var name: String var age = 0}let dog1 = Dog(name: "tom", age: 1)let dog2 = Dog(name: "tom", age: 1)dog1 == dog2 // truelet dog3 = Dog(name: "tom", age: 1)let dog4 = Dog(name: "tom", age: 2)dog3 == dog4 // falsestruct Dog遵照Equatable协议但没有实现协议方法着实例dog1与dog2实例相当,dog3与dog3实例不相当
- 数组等容器类(数组/字典等)内部的元素须要遵照Equatable才气实现一些本领,比方contains(_
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]let nameToCheck = "Kofi"if students.contains(nameToCheck) { print("\(nameToCheck) is signed up!") // Prints "Kofi is signed up!"} else { print("No record of \(nameToCheck).")}
- swift standard library中的大部门基础范例默认已经遵照Equatable,比方Int/Array/Dictionary/Set
- struct重的属性假如有不遵守Equatable,那么着实例无法用==
class MyClassNoEquatable { }struct NoEquatableStruct: Equatable { var mc = MyClassNoEquatable() }let nes1 = NoEquatableStruct()let nes2 = NoEquatableStruct()nes1 == nes2上面代码会报错,提示Type 'NoEquatableStruct' does not conform to protocol 'Equatable'
协议间的关联
Hashable协议基于Equatable协议,对于struct遵守Hashable并不须要实现Equatable方法,但是对于class遵守Hashable必须要实现Equatable的方法
Comparable协议基于Equatable
==与===
- Equatable本质是对属性的值对比,实用范围有struct/class/enum
- ===是对class实例指针的对比,且仅实用于class实例
class IntegerRef: Equatable { let value: Int init(_ value: Int) { self.value = value } static func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool { return lhs.value == rhs.value }}let a = IntegerRef(100)let b = IntegerRef(100)print(a == a, a == b, separator: ", ") // Prints "true, true"let c = aprint(c === a, c === b, separator: ", ") // Prints "true, false"参考
Equatable
Swift Equatable |