Swift通用数字类型和数学

前端之家收集整理的这篇文章主要介绍了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函数相同的结果操作数具有相同的符号.

猜你在找的Swift相关文章