繁体   English   中英

Swift将Integer转换为Int

[英]Swift convert Integer to Int

我正在进行泛型编程,并且有一些符合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)'的参数列表调用类型'Int'的初始值设定项

首先,错误可能更有用,因为CountableRange将其Bound.Stride定义为SignedIntegersource )。 所以这个错误可以告诉我。

所以我知道它是一个Integer ,但我如何实际使用Integer数值呢?

您可以使用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编译所upperBound + amountToMove

这应该适用于从swift 3.0开始

let theCount:Int32 = Int32(count);

如果您确实需要Int ,请尝试以下方法:

let theCount = Int(count.toIntMax())

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM