我想在Swift中转换浮点数为Int。像这样的基本强制转换不起作用,因为这些类型不是基本类型,不像Objective-C中的float和int类型

var float: Float = 2.2
var integer: Int = float as Float

但是这会产生以下错误消息:

Float不能转换为Int

知道如何将属性从Float转换为Int吗?


当前回答

var i = 1 as Int

var cgf = CGFLoat(i)

其他回答

这里介绍的大多数解决方案对于较大的值都会崩溃,不应该在生产代码中使用。

如果你不关心非常大的值,使用这段代码来夹紧Double到max/min Int值。

let bigFloat   = Float.greatestFiniteMagnitude
let smallFloat = -bigFloat

extension Float {
    func toIntTruncated() -> Int {
        let maxTruncated  = min(self, Float(Int.max).nextDown)
        let bothTruncated = max(maxTruncated, Float(Int.min))
        return Int(bothTruncated)
    }
}

// This crashes:
// let bigInt = Int(bigFloat)

// this works for values up to 9223371487098961920
let bigInt   = bigFloat.toIntTruncated()
let smallInt = smallFloat.toIntTruncated()

使用Int64而不是Int。Int64可以存储大的int值。

使用函数样式的转换(参见“Swift编程语言”中的“整数和浮点转换”一节)。(iTunes链接))

  1> Int(3.4)
$R1: Int = 3

是这样的:

var float:Float = 2.2 // 2.2
var integer:Int = Int(float) // 2 .. will always round down.  3.9 will be 3
var anotherFloat: Float = Float(integer) // 2.0

有很多方法可以精确地取整数。您最终应该使用swift的标准库方法roundaround()来以所需的精度舍入浮点数。

取整use .up规则:

let f: Float = 2.2
let i = Int(f.rounded(.up)) // 3

向下舍入使用.down规则:

let f: Float = 2.2
let i = Int(f.rounded(.down)) // 2

要四舍五入到最接近的整数,请使用.toNearestOrEven规则:

let f: Float = 2.2
let i = Int(f.rounded(.toNearestOrEven)) // 2

请注意以下示例:

let f: Float = 2.5
let i = Int(roundf(f)) // 3
let j = Int(f.rounded(.toNearestOrEven)) // 2