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'
协议间的关联
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"参考