微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift通用数字类型和数学

我试图围绕 Swift泛型的来龙去做,并制作一些常见的数学函数.我正在尝试实现一个mod函数,但不太确定使用泛型使其工作的最佳方法.

这是我的mod函数的样子:

func mod<N: NumericType,I: IntegerType>(_ x: N,_ y: I) -> N {
    return x - y * floor(x/y)
}

但是我收到了这个错误

error: binary operator '/' cannot be applied to operands of type 'N' and 'I'
    return x - y * floor(x/y)

这是我的十进制和整数类型数字的NumericType声明:

protocol NumericType: Comparable {
    static func +(lhs: Self,rhs: Self) -> Self
    static func -(lhs: Self,rhs: Self) -> Self
    static func *(lhs: Self,rhs: Self) -> Self
    static func /(lhs: Self,rhs: Self) -> Self
    static func %(lhs: Self,rhs: Self) -> Self
}

protocol DecimalType: NumericType {
    init(_ v: Double)
}

protocol IntegerType: NumericType {
    init(_ v: Int)
}

extension CGFloat : DecimalType { }
extension Double  : DecimalType { }
extension Float   : DecimalType { }

extension Int     : IntegerType { }
extension Int8    : IntegerType { }
extension Int16   : IntegerType { }
extension Int32   : IntegerType { }
extension Int64   : IntegerType { }
extension UInt    : IntegerType { }
extension UInt8   : IntegerType { }
extension UInt16  : IntegerType { }
extension UInt32  : IntegerType { }
extension UInt64  : IntegerType { }

解决方法

从Swift 3开始,所有浮点类型都符合FloatingPoint,
并且所有整数类型都符合Integer.
两种协议都定义了基本的算术运算,如 –,*,/.
另外,floor()函数是为FloatingPoint定义的
参数.

因此,在您的情况下,我将定义两个实现,一个用于
整数和一个浮点值:

func mod<N: Integer>(_ x: N,_ y: N) -> N {
    return x - y * (x/y) // or just: return x % y
}

func mod<N: FloatingPoint>(_ x: N,_ y: N) -> N {
    return x - y * floor(x/y)
}

FloatingPoint还有一个truncatingRemainder方法,a.truncatingRemainder(b)是“浮点等价物”到整数的%b.它给了如果两者都给出与mod函数相同的结果操作数具有相同的符号.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐