[英]Swift generic number types and math
我试图围绕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)
是整数a % b
的“浮点等价”。 如果两个操作数具有相同的符号,则它给出与mod
函数相同的结果。
static func /(lhs: Self, rhs: Self) -> Self
这意味着lhs
和rhs
必须属于同一类型 。
在x / y
, x
是N
型, y
是I
型。 所以x
和y
有不同的类型 ,因此x / y
不起作用。
你需要投y
从I
到N
第一:
let numericY = N(integer: y)
return x - numericY * floor(x / numericY)
这意味着你的NumericType需要能够从IntegerType初始化,除了有+
, -
, *
, /
, %
。
protocol NumericType: Comparable {
init<I: IntegerType>(integer: I)
...
}
(另外, floor<N: NumericType>(n: N) -> N
应该存在以使整个表达式编译。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.