Subscribe now

Details of Built-in Numeric Types [11.09.2016]

Floating Points

Swift has 3 built-in floating-point types, Float32, Float64, and Float80. In terms of the values these types can represent, they are your standard IEEE 754 values, i.e. just like float and double in C-based languages.

  var aFloat:Float32 = 0.123456789  //0.1234568

Float32s will hold around 7 significant figures, which is good enough for games and many non-scientific applications.

var aDouble:Float64 = 0.12345678012345678  //0.1234567801234568

Float64s hold around twice that many significant figures, which is why they are nicknamed Double.

Keep in mind that these are binary types, not decimal types, so some human-readable values, like 0.1 cannot be represented exactly. For instance, If I subtract 0.10000001 from 0.1, I should get 1e-8. But if I use a Float32, I get -7.45e-9. If this is problematic, you’ll need to use a wider type.

Integer Bitwise Literals

Sometimes, you may need to work with integers with particular bit patterns. In addition to initializing integers with regular radix-10 numbers, you can input hex or binary

var anInteger:Int = 0b00101010

And in the variable side bar you’ll see 42. That means the bits are Most-Significant Bit first when written this way, although all of Apple’s current devices are little endian.

Similarly, hex values are written as 0x :

var aHexValue:Int = 0xA2f4

Notice that capitalization was not important for hex values, and any more significant bits are assumed to be 0’s.