I want to convert a Float
to an Int
in Swift. Basic casting like this does not work because these types are not primitives, unlike float
Suppose you store float value in "X"
and you are storing integer value in "Y"
.
Var Y = Int(x);
or
var myIntValue = Int(myFloatValue)
var floatValue = 10.23
var intValue = Int(floatValue)
This is enough to convert from float
to Int
You can type cast like this:
var float:Float = 2.2
var integer:Int = Int(float)
Converting is simple:
let float = Float(1.1) // 1.1
let int = Int(float) // 1
But it is not safe:
let float = Float(Int.max) + 1
let int = Int(float)
Will due to a nice crash:
fatal error: floating point value can not be converted to Int because it is greater than Int.max
So I've created an extension that handles overflow:
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
}
}
}
I hope this can help someone
Like this:
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
Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])
1> Int(3.4)
$R1: Int = 3