How does Swift determine if two structures are equal?
In Swift, you can determine if two struct are equal by conforming to the Equatable protocol.
First, the Equatable protocol needs to be implemented for the struct and the implementation of the equality operator (==) needs to be defined. Here is an example:
struct Person: Equatable {
var name: String
var age: Int
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age
}
}
In the example above, we implemented the Equatable protocol for the Person structure and checked if the name and age properties of two structures are equal in the implementation of the == operator.
Next, you can use the == operator to determine if two Person structs are equal. For example:
let person1 = Person(name: "John", age: 25)
let person2 = Person(name: "John", age: 25)
if person1 == person2 {
print("两个结构体相等")
} else {
print("两个结构体不相等")
}
In the example above, the judgment result is “the two structures are equal” because the name and age attributes of person1 and person2 are the same.
If the Equitable protocol is not followed and the equality operator is not implemented, Swift will default to using the default equality judgment rule, which checks if two structures have the same attribute values. In certain cases, customizing the equality judgment rule may be necessary, requiring the manual implementation of the Equatable protocol and equality operator.