Search code examples
swiftindexofequatable

Index(of:) and Equatable Protocol


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.


Solution

  • Ask yourself this: what does index(of:) do exactly?

    It finds the index of the specified element in the array. Right? In other words, it finds the index of the first element that is equal to the parameter.

    A simple implementation for index(of:) would be to loop through the array and in each iteration, check whether the element is equal to the parameter. If it is, return the index. As you can see, this involves checking whether two objects are equal, so the Equatable protocol is required.