generics - 快速从通用数学类型返回 Int

标签 generics math swift

提到了如何要求泛型类型在数学运算中可用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/

相关文章:

swift - 通用工厂方法和类型推断

java - Java Math.pow 的错误结果

ios - Xcode 7 iOS 应用程序无法在设备上运行

algorithm - 跟踪累加结果,无反操作

ios - 如何将视频添加到 Storyboard页面 (Xcode 6)

ios - 想要将图像直接从图像选择器传输到另一个具有 uiimageview 的 View

typescript :获取实例的通用类型

java - 我怎样才能获取这个工作代码并使其使用java泛型?

java - 如何通过实例获取列表的所有元素?

javascript - 用于输入从实数到实数的函数的 Web UI,例如概率分布