[英]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.