Generic-type extension with a new generic type in Swift

58 views Asked by At

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!

1

There are 1 answers

0
Martin R On BEST ANSWER

You can put a constraint on the method instead:

extension Array {
    func merge<T>() -> T? where Element == T? {
        // ...
    }
}