Junior — Middle
What steps are necessary to implement the Equatable protocol conformance in Swift?
sobes.tech AI
Answer from AI
To make a structure in Swift conform to the Equatable protocol, you need to:
- Declare conformance to the protocol in the structure declaration.
- Implement the
==function that compares two instances of the structure for equality.
Starting with Swift 4.1, the compiler can automatically generate the == implementation for structures if all their properties also conform to Equatable.
Example:
struct Point: Equatable {
var x: Int
var y: Int
}
// Automatically generated implementation:
// static func == (lhs: Point, rhs: Point) -> Bool {
// return lhs.x == rhs.x && lhs.y == rhs.y
// }
let p1 = Point(x: 1, y: 2)
let p2 = Point(x: 1, y: 2)
print(p1 == p2) // true
If you need custom comparison, you can implement the operator yourself:
struct Person: Equatable {
var name: String
var age: Int
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name.lowercased() == rhs.name.lowercased() && lhs.age == rhs.age
}
}