2014-12-05 24 views
2

返回诠释如何需要一个泛型类型是可用在数学运算中提到here从一个普通的数学式的迅速

害得我这个协议

protocol MathematicsProtocol : Equatable 
{ 
    init(_ value: Int) 
    init(_ value: Float) 
    init(_ value: Double) 

    func + (lhs: Self, rhs: Self) -> Self 
    func - (lhs: Self, rhs: Self) -> Self 
    func * (lhs: Self, rhs: Self) -> Self 
    func/(lhs: Self, rhs: Self) -> Self 
} 
extension Int: MathematicsProtocol {} 
extension Float: MathematicsProtocol {} 
extension Double: MathematicsProtocol {} 

在这个片段中使用

struct MyRange<DataType : MathematicsProtocol> 
{ 
    let start : DataType 
    let end : DataType 
    let step : DataType 

    subscript(index: Int) -> DataType 
    { 
     get { 
      assert(index < self.count) 
      return start + DataType(index) * step 
     } 
    } 

    var count : Int { 
     return Int((end-start)/step) //not working 
//  return 4 
    } 
} 

但是,在count函数中将DataType转换为Int不起作用。 有没有办法解决这个问题?

编辑: 这个工作,但它是一个丑陋的黑客使用字符串作为临时值。

func convert<DataType : MathematicsProtocol>(value : DataType) -> Int 
{ 
    let intermediate = "\(value)" as NSString 
    return intermediate.integerValue 
} 
+0

为什么在迅速没有默认MathematicsProtocol? – kelin 2015-06-18 15:27:07

回答

2

必须定义一个MathematicsProtocol如何转换为一个Int,例如 通过添加intValue属性的协议:

protocol MathematicsProtocol { 
    // ... 
    var intValue : Int { get } 
} 
extension Int: MathematicsProtocol { 
    var intValue : Int { return self } 
} 
extension Float: MathematicsProtocol { 
    var intValue : Int { return Int(self) } 
} 
extension Double: MathematicsProtocol { 
    var intValue : Int { return Int(self) } 
} 

然后你可以使用它作为

var count : Int { 
    return ((end-start)/step).intValue 
} 
+0

辉煌。很棒。 我尝试了类似的方式,增加了一个init (_ value:T),但那是一个死胡同。无法获得正确的类型。 – user965972 2014-12-05 20:11:43