class Person: Equatable {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
static func ==(lhs: Person, rhs: Person) -> Bool {
return (lhs.name == rhs.name) && (lhs.age == rhs.age)
}
}
let p1 = Person(name: "David", age: 29)
let p2 = Person (name: "John", age: 28)
var people = [Person]()
people.append(p1)
people.append(p2)
let p1index = people.index(of: p1)
let p2index = people.index(of: p2)
In order to use index(of:)
, i need to conform Person to Equatable protocol. From what i know, Equatable protocol allows 2 instances to be compared for equality. What is the relation between finding an index and compare for equality? Why I must conform to Equatable protocol in order to use index(of:)
?
To adopt the Equatable protocol, I must implement the (==)
operator as a static method:
static func ==(lhs: Person, rhs: Person) -> Bool {
return (lhs.name == rhs.name) && (lhs.age == rhs.age)
}
I am not comparing any Person instances for equality here, why do I still need to return (lhs.name == rhs.name) && (lhs.age == rhs.age)
? What is it for? Does it have anything to do with index(of:)
?
Sorry for asking this stupid question.