提到了如何要求泛型类型在数学运算中可用here
这让我想到了这个协议(protocol)
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
转换为 Int
,例如
通过向协议(protocol)添加 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
}
关于generics - 快速从通用数学类型返回 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321763/