Is there a way to write an extension referencing an instance with an associated type

Is there a way to write an extension referencing an instance with an associated type. I have the feeling that it is something that is supported one way or another.

Something like:

struct S<A> {
    let s: A

    init(s: A) {
        self.s = s
    }
}

extension Array where Element == S<T> {

    func getAllS() -> [T] {
        return map({ $0.s })
    }

}

You can do this if T is a concrete type. If not you’re probably looking for parameterized extensions.

1 Like

@Val Yeah. It seems it is nit possible in current iteration. Thanks for help.

Define a protocol SProtocol, to which only S conforms:

protocol SProtocol {
    associatedtype A
    var s: A { get }
}

extension S: SProtocol { }

extension Array where Element: SProtocol {
    func getAllS() -> [Element.A] {
        return map { $0.s }
    }
}

You can also write a general extension, and constrain the function by its parameters, including new generic arguments:

extension Array { // ← non-constrained extension
  func getAllS<T>() -> [T] where Element == S<T> { // ← constrained function
    map(\.s)
  }
}
6 Likes