Klas Zetterlund Klas Zetterlund - 1 month ago 6
Swift Question

Finding value in array containing custom class

I'm trying to find the place of a value in a an array containing structures.
My array looks like this

struct User {
var firstName: String?
var lastName: String?
}

var allThePeople = [User(firstName: "John", lastName: "Doe"), User(firstName: "Jane", lastName: "Doe"), User(firstName: "John", lastName: "Travolta")];


Is there a way to get the places for all "Doe"'s in the array? (in this case 0 and 1)

Answer

If you want the actual indices, use something like

struct User {
    var firstName: String?
    var lastName: String?
}

var allThePeople = [User(firstName: "John", lastName: "Doe"), User(firstName: "Jane", lastName: "Doe"), User(firstName: "John", lastName: "Travolta")]

var indices = [Int]()
for i in 0 ..< allThePeople.count {
    if allThePeople[i].lastName == "Doe" {
        indices.append(i)
    }
}
indices // [0,1]

otherwise use filter as @Callam suggested.

Comments