编译器告诉我
Expression type '([String]) -> Bool' is ambiguous without more context
我不知道如何在语句中添加更多上下文。我以为扩展声明会告诉函数它需要的关于集合中元素的所有信息。我在代码片段中留下了更多的想法。寻找标有“!!! 编译错误!!!"
您应该能够将代码复制并粘贴到空项目中,以查看编译错误。
protocol Measurement {
var id: String { get }
var displayPriority: Int { get }
}
extension Collection where Element: Collection, Element.Element: Measurement {
func contains(ids: [String]) -> Bool {
return self.filter{ measurementCollection -> Bool in
// !!! COMPILE ERROR !!!
// Error: Expression type '([String]) -> Bool' is ambiguous without more context
//
// The compiler doesn't under stand that this is a collection of Measurement,
// Do I somehow need to tell the compiler that the elements to the collection
// or collections with elements with a type that is a kind of Measurement again?
// I thought the extension declaration already specified everything it needed.
return measurementCollection.isEquals(ids: ids)
}.count > 0
}
}
extension Collection where Element == Measurement {
func isEquals(ids: [String]) -> Bool {
// get all the IDs
let allIDs = self.map{ $0.id }
// convert it to a set to make comparisons easier
return Set(allIDs) == Set(ids)
}
}
func whatIwantToDo() {
let measurements = [[ConcreteMeasurement("A")],
[ConcreteMeasurement("B")],
[ConcreteMeasurement("C"), ConcreteMeasurement("D")]
]
let ids = ["C", "D"]
// Ultimately, I want to fix my compile error to run the following line of code, this should output to True
print("Does measurements contain: \(ids) -> \(measurements.contains(ids: ids))" )
}
最佳答案
第一个扩展名具有约束条件Element.Element: Measurement
,
这意味着在闭包中,measurementCollection
是
元素类型采用Measurement
协议。
因此,为了从这个集合的第二个扩展调用isEquals()
方法,它必须定义为
extension Collection where Element: Measurement { // Not: Element == Measurement
func isEquals(ids: [String]) -> Bool { ... }
}
还要注意,一般来说,测试
filter { ... }.count > 0
更有效的方法是
contains(where: { ... })