【问题标题】:Swift convert Integer to IntSwift 将 Integer 转换为 Int
【发布时间】:2017-05-05 16:55:35
【问题描述】:

我正在做泛型编程并且有一些符合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 定义为SignedInteger (source)。所以错误可能会告诉我。

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

【问题讨论】:

    标签: swift


    【解决方案1】:

    您可以使用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 编译。

    【讨论】:

      【解决方案2】:

      这应该适用于您从 swift 3.0 开始

      let theCount:Int32 = Int32(count);
      

      【讨论】:

        【解决方案3】:

        如果你真的需要那个Int,试试这个:

        let theCount = Int(count.toIntMax())
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-12-26
          • 1970-01-01
          • 2017-06-29
          • 1970-01-01
          • 1970-01-01
          • 2013-11-26
          • 2020-10-29
          相关资源
          最近更新 更多