Search code examples
arraysswiftopaque-result-type

Return an opaque type of array


Is it possible to return some [T] ?

protocol P {
    associatedtype X
    func method() -> [X]
}

class Imp: P {
    typealias X = Int

    func method() -> some [Int] {
        return [1]
    }
}

Code above produces error "An 'opaque' type must specify only 'Any', 'AnyObject', protocols, and/or a base class"

EDIT: Diagram So protocol hides underlying @NSMangedObject and expose only needed properties. It would be nice if A, B have Comparable capabilities.


Solution

  • This isn't possible, but that's because it doesn't mean anything. some T means "a specific, concrete type that conforms to T, known by the returning function at compile time, but not known by the caller." [Int] is a type known to the caller. There is nothing "opaque" about it. This is identical to:

    func method() -> [Int] { ... }