Swift将整数转换为Int

3

我正在进行泛型编程,并拥有符合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)上。具体错误信息是:

Cannot invoke initializer for type 'Int' with an argument list of type '(Bound.Stride)'

首先,错误信息可以更有帮助一些,因为CountableRange将其Bound.Stride定义为SignedInteger (source)。所以错误信息本应该告诉我这一点。
现在我知道它是一个整数,但我该如何实际使用这个整数值呢?
3个回答

4
您可以使用 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
    }
}

为了使算术运算lowerBound - amountToMoveupperBound + amountToMove编译通过,需要使用限制条件Bound: Strideable


0

这应该适用于从Swift 3.0开始

let theCount:Int32 = Int32(count);

0
如果你真的需要那个 Int,可以尝试这个方法:
let theCount = Int(count.toIntMax())

toIntMax() 方法使用 Swift 的 最宽 本地有符号整数类型(即在 64 位平台上为 Int64)返回此整数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接