Ringo_D
Ringo_D

Reputation: 804

How to write generic constraint for optional type in Swift?

Once I write a generic constraint, it only fit the normal type, but not optional type. It will lead to a compiler error while I call it as optional type: Type 'SomeType? does not conform to protocol SomeProtocol'.

Here is the sample code:

protocol P {}

class C<T> {}

extension C where T: P {
    static func test() {}
}

extension Int: P {} // OK
C<Int>.test() // OK


extension Int?: P {} // Fail, but I need it
C<Int?>.test() // Fail, but I need it

Updated:

I find a way to solve it.

Here is the sample code.

protocol P {}

class C<T> {}

extension C where T: P {
    static func test() {}
}

extension Int: P {} // OK
C<Int>.test() // OK

protocol OptionalProtocol {
    associatedtype WrappedType
}

extension Optional: OptionalProtocol {
    typealias WrappedType = Wrapped
}

extension C where T: OptionalProtocol, T.WrappedType==Int {
    static func test() {}
}

C<Int?>.test() // OK now

Upvotes: 4

Views: 2610

Answers (1)

Dennis Vennink
Dennis Vennink

Reputation: 1183

It's currently not possible to do this.

extension Optional: P where Wrapped == Int {}

If we try to extend Optional where Wrapped is constrained to an Int the compiler will complain that "extensions with constraints cannot have inheritance clauses".

Note: This is currently being worked on under the SE-0143 proposal and should arrive in a future version of Swift.

Upvotes: 1

Related Questions