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

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

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

Float不能转换为Int

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


当前回答

是这样的:

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

其他回答

var floatValue = 10.23
var intValue = Int(floatValue)

这足以将float转换为Int

是这样的:

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

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

通过将浮点数传递给integer初始化方法,可以获得浮点数的整数表示形式。

例子:

Int(myFloat)

请记住,小数点后的任何数字都是负数。意思是,3.9是3的整数,8.99999是8的整数。

转换很简单:

let float = Float(1.1) // 1.1
let int = Int(float) // 1

但这并不安全:

let float = Float(Int.max) + 1
let int = Int(float)

将由于一次漂亮的碰撞:

fatal error: floating point value can not be converted to Int because it is greater than Int.max

所以我已经创建了一个处理溢出的扩展:

extension Double {
    // If you don't want your code crash on each overflow, use this function that operates on optionals
    // E.g.: Int(Double(Int.max) + 1) will crash:
    // fatal error: floating point value can not be converted to Int because it is greater than Int.max
    func toInt() -> Int? {
        if self > Double(Int.min) && self < Double(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}


extension Float {
    func toInt() -> Int? {
        if self > Float(Int.min) && self < Float(Int.max) {
            return Int(self)
        } else {
            return nil
        }
    }
}

我希望这能帮助到一些人