Use Equatable Protocol in Swift
Written by Team Kodeco
The Equatable protocol in Swift allows you to define equality between instances of a type. By conforming to this protocol, you can implement the == operator and determine whether two instances of your type are equal. The protocol is defined as follows:
public protocol Equatable {
static func ==(lhs: Self, rhs: Self) -> Bool
}
When two instances of a type that conforms to Equatable are compared with the == operator, the implementation of == is called to determine equality. If == returns true, the instances are considered equal. If == returns false, the instances are considered not equal.
For example, if you have a custom struct Person:
struct Person: Equatable {
let name: String
let age: Int
}
You can make two instances of Person equal by conforming to Equatable and implementing the == operator:
extension Person {
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age
}
}
Here is an example for using Person:
let person1 = Person(name: "John Doe", age: 30)
let person2 = Person(name: "Jane Doe", age: 25)
let person3 = Person(name: "John Doe", age: 30)
print(person1 == person2) // false
print(person1 == person3) // true