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
}
为什么在迅速没有默认MathematicsProtocol? – kelin 2015-06-18 15:27:07