2017-03-25 46 views
0

元素我有2类:如何返回一个包含搜索到的元素

- Favourite 
    + key 
    + showKey 
- Show 
    + key 

我有favouriteShows[Favourite] 数组我有一个演出对象show

检查,如果该节目的关键是我喜欢的一部分我做的:

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

但我也想确定哪个最喜欢它是有了showKey。

喜欢的东西let favouriteIndex = favouriteShows.contains(where: {$0.showKey == show.key})

+0

你甚至可以使用'第一(其中: )'像这个http://stackoverflow.com/a/42037292/6433023获取对象 –

回答

1

您正在寻找index(where:)

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

// use favouriteIndex 
0

或者,你可以枚举favouriteShows排列如下:

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