2016-07-29 106 views

回答

2

种。由于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