Jean-Baptiste
Jean-Baptiste

Reputation: 967

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!

Upvotes: 1

Views: 53

Answers (1)

Martin R
Martin R

Reputation: 540105

You can put a constraint on the method instead:

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

Upvotes: 1

Related Questions