grabury
grabury

Reputation: 5559

How to return the element that contains the searched for element

I have 2 classes:

- Favourite
    + key
    + showKey
 - Show
    + key

I have an array of favouriteShows [Favourite] I have a show object show

To check if the show's key is part of favouriteShows I do:

if favouriteShows.contains(where: {$0.showKey == show.key}) {
...
}

But I also want to identify which favourite it was that had the showKey.

Something like let favouriteIndex = favouriteShows.contains(where: {$0.showKey == show.key})

Upvotes: 0

Views: 29

Answers (2)

Fahim
Fahim

Reputation: 3556

Alternatively, you can enumerate the favouriteShows array as follows:

for (ndx, sh) in favouriteShows.enumerated() {
    if sh.showKey == show.key {
        // ndx contains the index at this point
    }
}

Upvotes: 0

Alexander
Alexander

Reputation: 63271

You're looking for index(where:)

guard let favouriteIndex = favouriteShows.index(where: {$0.showKey == show.key}) else {
    // no favourite matched
    return
}

// use favouriteIndex

Upvotes: 1

Related Questions