13

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
  • 18,342
  • 7
  • 61
  • 106
Alex_slayer
  • 213
  • 1
  • 3
  • 8

3 Answers3

25
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
  • 45,449
  • 17
  • 80
  • 115
Miknash
  • 7,775
  • 3
  • 32
  • 46
4

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
  • 14,647
  • 5
  • 57
  • 94
0

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

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

Alex_slayer
  • 213
  • 1
  • 3
  • 8