我的目标是要通过所有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
否?
我想念什么?
好吧,我找到了正确的语法,不确定为什么其他语法无法通过:/
如果有人仍然可以解释为什么其他方法不起作用,那将很有趣🤔
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) })
}
}