我正在努力理解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 { }