如何创建集扩展以在 属性 的集合中查找唯一对象?

How to create Set Extension to find unique object in the set with property?

查看了几个解决方案以找到数组中结构中的字段匹配的第一个元素,这里: Find object with property in array and here:

仅适用于 return 个匹配项,如果是单个唯一匹配项:

    var foundAction: SequenceAction?
    let filteredActions = currentStatus.seqActionsList.filter({[=11=].verb == actionCommand})
    if filteredActions.count == 1
    {
        foundAction = filteredActions.first
    }

继续使用此代码段,但不知道如何将其添加为 Set 的扩展?

集合已经有一个 indexOf 方法,可以让您使用谓词搜索成员。你可以使用它:

let numberSet: Set = [2, 4, 6, 8, 10, 12, 13]
if let index = numberSet.indexOf({ [=10=] % 2 == 1 }) {
    print(numberSet[index])
} else {
    print("No odd members found")
}

记录一下,最终弄明白了:

extension Set{
func findUniqueMatch(predicate: Element -> Bool) -> Element?
{
    let filteredList = self.filter(predicate)
    if filteredList.count == 1
    {
        return filteredList.first
    }

    return nil
}}