Swift Protocols
Equatable
- It’s a good idea for all your custom model types to conform.
- With
Equatableconformance, you can use the equal-to operator (==) or the not-equal-to operator (!=) with any two instances - To make a class conform to the
Equatableprotocol, declare conformance in an extension and implement the static==operator method. Compare each significant property for equality in your==method’s implementation:
extension Player: Equatable {
static func ==(lhs: Player, rhs: Player) -> Bool {
return lhs.name == rhs.name && lhs.position == rhs.position } }
Hashable
- It’s a good idea for all your custom model types to conform.
- To conform to the
Hashableprotocol, declare conformance in another extension and implement thehash(into:)method. In thehash(into:)method, call thecombine(_:)method on the provided hasher with each significant property:
extension Player: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(position)
}
}
*A type is eligible for automatic conformance to Equatable and Hashable when it’s a structure or an enumeration that meets these criteria:
- For a structure, all its stored properties must conform to
EquatableandHashable. - For an enumeration, all its associated values must conform to
EquatableandHashable. (Enumerations without associated values haveEquatableandHashableconformance even without declaring adoption.)* - Always use the same properties in both your
==andhash(into:)methods. Using different groups of properties in the two methods can lead to unexpected behavior or performance when using your custom type in sets and dictionaries.*