2015-06-21 292 views
1

有沒有什麼方法可以在Swift中描述IntegerType有一個max屬性? (類似於go中的隱式接口)Swift隱式協議

沒有協議來描述max屬性,即使我創建了一個,IntegerType也沒有明確實現它。

所以基本上我正在尋找類似:

class Test<T: IntegerType where ?> { // <- ? = something like 'has a "max: Self"' property 
} 

let t = Test<UInt8>() 

或也許是這樣的:

implicit protocol IntegerTypeWithMax: IntegerType { 
    static var max: Self { get } 
} 

class Test<T: IntegerTypeWithMax> { 
} 

let t = Test<UInt8>() 
+0

只需刪除「隱含」然後編譯... –

+0

@MartinR,它編譯,但它沒有做我想做的事情,因爲'IntegerType'沒有實現'IntegerTypeWithMax',所以我不能使用任何'IntegerType'(例如'UInt8')實例化一個類作爲參數。 – rid

+0

編譯器不知道符合'IntegerType'的所有類型是否具有'max'屬性。你必須告訴他如何'擴展UInt8:IntegerTypeWithMax {}'。 (Swift 2中的新協議擴展可能有更好的方法。) –

回答

1

雨燕編譯器不會自動推斷協議一致性 即使一個類型實現了所有的所需的屬性/方法。所以,如果你定義

protocol IntegerTypeWithMax: IntegerType { 
    static var max: Self { get } 
} 

你還必須讓你有興趣 整數類型符合該協議:

extension UInt8 : IntegerTypeWithMax { } 
extension UInt16 : IntegerTypeWithMax { } 
// ... 

擴展塊是空的,因爲UInt8UInt16已經有 一靜態max方法。

然後

class Test<T: IntegerTypeWithMax> { 
} 

let t = Test<UInt8>() 

編譯和運行正常。