2016-07-29 84 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