2017-05-05 46 views
2

我在做泛型編程,並且有一些符合Integer的內容。不知何故,我需要將其轉化爲我可以使用的具體Int迅速轉換爲整數的內容

extension CountableRange 
{ 
    // Extend each bound away from midpoint by `factor`, a portion of the distance from begin to end 
    func extended(factor: CGFloat) -> CountableRange<Bound> { 
     let theCount = Int(count) // or lowerBound.distance(to: upperBound) 
     let amountToMove = Int(CGFloat(theCount) * factor) 
     return lowerBound - amountToMove ..< upperBound + amountToMove 
    } 
} 

這裏的錯誤是在let theCount = Int(count)。其中規定:

不能調用類型「詮釋」初始化與類型「(Bound.Stride)」參數列表

首先,錯誤可能會更有幫助,因爲CountableRange定義其Bound.StrideSignedIntegersource)。所以錯誤可能告訴我這一點。

所以我知道這是一個Integer,但我怎麼實際上使用Integer價值?

回答

3

您可以使用numericCast() 在不同的整數類型之間進行轉換。如文檔 所述:

通常用於轉換爲任何上下文推導的整數類型。

你的情況:

extension CountableRange where Bound: Strideable { 

    // Extend each bound away from midpoint by `factor`, a portion of the distance from begin to end 
    func extended(factor: CGFloat) -> CountableRange<Bound> { 
     let theCount: Int = numericCast(count) 
     let amountToMove: Bound.Stride = numericCast(Int(CGFloat(theCount) * factor)) 
     return lowerBound - amountToMove ..< upperBound + amountToMove 
    } 
} 

的限制Bound: Strideable必要使算術 lowerBound - amountToMoveupperBound + amountToMove編譯。

+0

非常好,謝謝! –

0

這應該爲你從SWIFT 3.0

let theCount:Int32 = Int32(count); 
0

開始工作,如果你真的很需要那Int,試試這個:

let theCount = Int(count.toIntMax()) 

toIntMax()方法使用雨燕的最大本地返回此整數有符號整數類型(即在64位平臺上的Int64)。