暧昧调用集合扩展功能(Ambiguous call to Collection extension

2019-10-29 18:43发布

编译器告诉我,

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))" )
}

Answer 1:

所述第一延伸部具有约束Element.Element: Measurement ,这意味着在所述封闭, measurementCollection是一个集合,其元素类型采用 Measurement协议。

因此,为了调用isEquals()从该集合的第二扩展方法,它必须被定义为

extension Collection where Element: Measurement { // Not: Element == Measurement
    func isEquals(ids: [String]) -> Bool { ... }
}

还需要注意的是通常,测试

filter { ... }.count > 0

为更有效地完成如

contains(where: { ... })


文章来源: Ambiguous call to Collection extension function