Как ограничить тип элемента для массива, если он является элементом другого массива - PullRequest
0 голосов
/ 12 сентября 2018

У меня есть массив внутри ситуации с массивом, и я хочу ограничить тип элемента внутреннего массива.

// 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 []
    }
}

1 Ответ

0 голосов
/ 12 сентября 2018

Это гораздо проще реализовать как расширение для всех коллекций, а не только для массивов. Я считаю, что расширение, которое вы хотите, это:

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

Основная проблема заключается в том, что в Swift отсутствуют типы с более высоким родом, поэтому вы не можете расширять Array (потому что это неправильный тип). Но вы можете расширить Collection (потому что это PAT).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...