看了几个解决方案,找到一个结构中字段匹配的数组中的第一个元素,这里: Find object with property in array和此处:find object in array
仅适用于在一次唯一匹配时返回匹配项:
var foundAction: SequenceAction?
let filteredActions = currentStatus.seqActionsList.filter({$0.verb == actionCommand})
if filteredActions.count == 1
{
foundAction = filteredActions.first
}
继续使用此代码段,但无法确定如何添加为Set?
的扩展名答案 0 :(得分:0)
集已有indexOf
方法,可让您搜索带谓词的成员。你可以使用它:
let numberSet: Set = [2, 4, 6, 8, 10, 12, 13]
if let index = numberSet.indexOf({ $0 % 2 == 1 }) {
print(numberSet[index])
} else {
print("No odd members found")
}
答案 1 :(得分:0)
为了记录,最终想出来了:
extension Set{
func findUniqueMatch(predicate: Element -> Bool) -> Element?
{
let filteredList = self.filter(predicate)
if filteredList.count == 1
{
return filteredList.first
}
return nil
}}