2015-06-21 301 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>() 

编译和运行正常。