Index of an element in array

Viewed 68

For example, I have following class:

class Person: Any {
    dynamic var name: String = ""
    dynamic var surname: String = ""
}

Also, I have following array with instances of "Person" class:

let person1 = Person(); person1.name = "John"; person1.surname = "Smith"
let person2 = Person(); person2.name = "Ivan"; person2.surname = "Ivanov"
let person3 = Person(); person3.name = "Sam"; person3.surname = "Woodman"
let personList = [person1, person2, person3]

Is there a way of somehow getting indexes of all Johns?

1 Answers

You can flatMap your list of persons as an enumerated list so to return the matching offsets.

let indexes = personList.enumerated().flatMap { $1.name == "John" ? $0 : nil }

Otherwise, you can achieve this with a simple for loop.

var indexes = [Int]()

for index in personList.indices {
    if personList[index].name == "John" {
        indexes.append(index)
    }
}

print(indexes)
Related