1

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)

1
  • You want the filtered array or the indexes for your condition? Commented Oct 26, 2016 at 12:46

2 Answers 2

3

You can filter allThePeople with a condition to get all the people with the last name "Doe".

let allTheDoes = allThePeople.filter { $0.lastName == "Doe" }

You can enumerate the array and flat map it to an array of indices.

let allTheDoeIndexes = allThePeople.enumerated().flatMap { $0.element.lastName == "Doe" ? $0.offset : nil }
                     = allThePeople.enumerated().flatMap { $1.lastName == "Doe" ? $0 : nil }
Sign up to request clarification or add additional context in comments.

4 Comments

The closure can be shortened slightly to { $1.lastName == "Doe" ? $0 : nil } – perhaps a matter of taste.
Your flatmap is way more concise than my for loop answer (I upvoted you) - but it may be too terse for a novice - consider adding a bit of explanation?
Could I add more filters? Say I wanted to find the indices for all names with lastname Doe AND firstname John?
Yes you could do this allThePeople.enumerated().flatMap { $1.firstName == "John" && $1.lastName == "Doe" ? $0 : nil }
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.