Search code examples
swiftcastingtype-conversion

Convert Float to Int in Swift


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 floats and ints in Objective-C

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

But this produces the following error message:

'Float' is not convertible to 'Int'

Any idea how to property convert from Float to Int?


Solution

  • You can convert Float to Int in Swift like this:

    var myIntValue:Int = Int(myFloatValue)
    println "My value is \(myIntValue)"
    

    You can also achieve this result with @paulm's comment:

    var myIntValue = Int(myFloatValue)