1

I'd like to extend the generic type Array<Element> with a constraint on Element that depends on another generic type, such as Element == Optional<Wrapped>.

In the case where Element is not generic, it is easy:

extension Array where Element == String {
    func merge() -> String { ... }
}

I tried the following, but the compiler does not accept it.

extension Array<Wrapped> where Element == Optional<Wrapped> {
    func merge() -> Optional<Wrapped> { ... }
}

What syntax should I use in this case? Thanks in advance!

Jean-Baptiste
  • 907
  • 8
  • 17

1 Answers1

1

You can put a constraint on the method instead:

extension Array {
    func merge<T>() -> T? where Element == T? {
        // ...
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382