cfischer
cfischer

Reputation: 24912

extend a concrete instance of a generic type in Swift

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

Answers (1)

pgb
pgb

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

Related Questions