swiftgenericsclass-extensions

Generic-type extension with a new generic type in Swift


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!


Solution

  • You can put a constraint on the method instead:

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