Reputation: 24912
Is it possible to provide an extension that only applies to a specific instance of a generic type?
For example, say I want to add a method to Int?
, but not to any other Optional
.
Is this possible?
Upvotes: 2
Views: 576
Reputation: 25001
Kind of. Since Optional
is a protocol, you can create an extension and constrain it. However, the constraint can't be on a type, but needs to be on a protocol.
This works:
extension Optional where Wrapped: SignedIntegerType {
func test() -> Int {
return 0
}
}
and then you can use it:
let a:Int? = nil
a.test()
However, if you try to do:
extension Optional where Wrapped: Int {
func test() -> Int {
return 0
}
}
you'll get an error:
type 'Wrapped' constrained to non-protocol type 'Int'
Upvotes: 3