簡體   English   中英

Swift通用數字類型和數學

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

這意味着lhsrhs必須屬於同一類型

x / yxN型, yI型。 所以xy不同的類型 ,因此x / y不起作用。

你需要投yIN第一:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM