arrays - 当一个数组是另一个数组的元素时如何限制它的元素类型

标签 arrays swift where-clause associated-types

我有一个数组,在数组情况下,我想限制内部数组的元素类型。

// this doesn't work but should illustrate what I want. Is there
// any way to constrain the Element type for an Array when it's
// already declared as the type for an Array 
extension Array where Element == Array<Element2: SomeProtocol> { 
}

最终,我认为解决这个问题将修复以下编译错误

protocol Thingy {
    associatedtype MeasurementType: Measurement

    var topMeasurements: [[MeasurementType]] { get }
}

extension Thingy {
    func doStuff() {

        // COMPILE ERROR'[[Self.MeasurementType]]' is not convertible to 'Array<Array<Measurement>>'
        let compileError = self.topMeasurements.measurements(forUUIDs: ["A"])

        // Hack workaround
        // The fact that this works leads me to believe that the constraint in the
        // extension is inadequate. The extension wants [[Measurement]] and 
        // event though MeasurementType is a kind of Measurement the compiler won't 
        // allow it. The hope is that if we could write something like 
        // [[Element]] where Element: Measurement
        let measurements: [[Measurement]] = self.topMeasurements
        let thisWorks = measurements.doSomething(ids: ["A"])
        print(thisWorks)
    }
}

// I'm hoping that if I constrain the following that it'll fix my issue
// constrain this type ----------------------
//                                          |
//                                          \/
extension Array where Element == Array<Measurement> {
    func doSomething(ids: [String]) -> [Measurement] {
        // do something return some elements, 
        // I've removed any code that could cause confusion
        return []
    }
}

最佳答案

作为对所有集合的扩展,这比仅在数组上更容易实现。我相信你想要的扩展是这样的:

extension Collection where Element: Collection, Element.Element: Measurement {
    func measurements(forUUIDs: [String]) -> [Measurement] {
        return []
    }
}

基本问题是 Swift 缺少更高种类的类型,因此您不能扩展 Array(因为那不是合适的类型)。但是您可以扩展 Collection(因为那是 PAT)。

关于arrays - 当一个数组是另一个数组的元素时如何限制它的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301374/

相关文章:

python - 根据数组元素创建变量名

javascript - 如何在 JavaScript 中将 JSON 对象转换为字符串和数字数组

javascript - 查找时间 t 的所有数组元素

ios - 如何将新的 Sprite 附加到移动的 Sprite 上?

Swift + Alamofire - 验证并获取 XML 文件

ios - 获取实体数组中的最高日期。

mysql - SQL Select Query中的Where条件算法

c# - 动态生成 Linq/Lambda Where 子句

arrays - Golang问题数组数独-网格[i] [j] [0]

mysql - 如何获取过滤数据的总和