16

I can't figure out how to find index of object in array. For example I have this data structure:

class Person {
var name: String
var age: Int

init(name personName: String, age personAge: Int) {
    self.name = personName
    self.age = personAge
  }
}

let person1 = Person(name: "person1", age: 34)
let person2 = Person(name: "person2", age: 30)
...
var personsArray = [person1, person2, ...]

I tried to use personsArray.index(where: ....) but I don't understand how to use it. index(of: ...) doesn't work. I think because personsArray doesn't conform to Equatable protocol...

shallowThought
  • 19,212
  • 9
  • 65
  • 112
Alex_slayer
  • 243
  • 1
  • 3
  • 8

3 Answers3

27
index(of: )

gets the Person in your case - it is generic function.

index(where: ) 

gets the condition for which you want to find particular Person

What you could do:

personsArray.index(where: { $0.name == "person1" })

Or you could send object to:

personsArray.index(of: existingPerson)

For both options you could get nil - you will have to check it for nil (or guard it).

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Miknash
  • 7,888
  • 3
  • 34
  • 46
5

From my point of view just compare with ===.

Small example.

func getPersonIndex(from: [Person], user: Person) -> Int? {
    return from.index(where: { $0 === user })
}

getPersonIndex(from: personsArray, user: person2)
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
0

I found how to use .index(where...

personsArray.index { (item) -> Bool in item.name == "person2" && item.age == 30 }

Alex_slayer
  • 243
  • 1
  • 3
  • 8