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