This guide has been updated to work with Swift 3 — If you’re using an older version of Swift, some code samples may not work.
An integer is a whole number, with no fractional component – Example: 15 or -13. There are two types of integers, signed and unsigned. Signed integers have a positive, zero or negative value. Unsigned integers can only be positive or 0. When you create an Int and don’t declare the type, Swift assumes it to be signed. In most cases, you don’t need to pick a size (32/64) for your integers as they automatically default to the current platform’s native word size. Example: Your platform is 64 bit, Int is the same as Int64. Your platform is 32 bit, Int is the same as Int32.
How to create an Int (Signed)
To create a signed int (a number that has a positive, zero or negative value).
var myInt:Int = -5 //Created a signed Int
How to create an (Unsigned) Int
To create an unsigned in (a number that can only be positive or zero), use the type UInt.
var myUnsignedInt : UInt = 52 //Works. var myOtherUnsignedInt : UInt = -5 //Doesn't compile, unsigned Ints can't be negative!
Convert String to Int
You can easily convert a Swift string to an integer by using the .toInt() method.
let currentAge = "30" //Our string value let ageInteger = currentAge.toInt() //Convert to Int println(ageInteger!) //Unwrap the returned optional by adding an exclamation point.
Convert Double/Float to Int
Convert a number with a fractional component (double or float) to an Int. Note, since Integers are whole numbers, converting a Double/Float to an Int will round down to the nearest whole number.
var myDoubleValue = 3.14 //Double var myIntValue = Int(myDoubleValue) println("The Int Value is \(myIntValue)")