序列的快速扩展,用于检查交点是否存在

问题描述 投票:0回答:1

我的目标是要通过所有Sequence提供一个函数,例如数组或集合。

此函数应返回一个Bool,以告知两个序列中是否存在至少一个对象。

// Usage
let s1 = ["hi", "hey", "ho"]
let s2:Set = ["woop", "oi", "yes"]

if s2.intersects(with: s1) {
  print("Happy me, it's a match")
}

extension Sequence where Element:Equatable {
    func intersects<T:Sequence>(with anotherSequence:T) -> Bool
    where T.Element: Equatable {
        //                  ⬇ error: `Extraneous argument label 'where:' in call`
        return self.contains(where: anotherSequence.contains)
    }
}

// doing the same function outside works:
let rez = s1.contains(where: s2.contains)
print(rez)

我觉得我快到了,但是我不明白为什么第一个contains(where:)会给我这个错误。contains()contains(where:)都属于Sequence否?

我想念什么?

swift sequence swift-extensions
1个回答
0
投票

好吧,我找到了正确的语法,不确定为什么其他语法无法通过:/

如果有人仍然可以解释为什么其他方法不起作用,那将很有趣🤔

extension Sequence where Element:Equatable {
    func intersect<T:Sequence>(with anotherSequence:T) -> Bool
        where T.Element == Self.Element {
        return self.contains(where: { anotherSequence.contains($0) })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.