在Swift中扩展泛型类型的具体实例

问题描述:

是否可以提供仅适用于泛型类型的特定实例的扩展?在Swift中扩展泛型类型的具体实例

例如,假设我想添加一个方法到Int?,但没有添加到其他Optional

这可能吗?

+1

只需扩展Int本身 –

种。由于Optional是一种协议,因此您可以创建扩展并对其进行约束。但是,约束不能在一个类型上,但需要在一个协议上。

这工作:

extension Optional where Wrapped: SignedIntegerType { 
    func test() -> Int { 
     return 0 
    } 
} 

,然后你可以使用它:

let a:Int? = nil 
a.test() 

但是,如果你尝试做:

extension Optional where Wrapped: Int { 
    func test() -> Int { 
     return 0 
    } 
} 

,你会得到一个错误:

type 'Wrapped' constrained to non-protocol type 'Int'

+0

请注意,调用该方法时,必须调用它,因为它是非可选的。 –

+1

是的,这使它看起来很奇怪,恕我直言。 – pgb