A whole lot of number types

You’ve been using Int to represent whole numbers. An Int is represented with 64- bits on most modern hardware and with 32-bits on older, or more resource constrained systems. Swift provides many more number types that use different amounts of storage. For whole numbers, you can use the explicit signed types Int8, Int16, Int32, Int64. These types consume 1, 2, 4, and 8 bytes of storage respectively. Each of these types use 1-bit to represent the sign.

If you are only dealing with non-negative values there are a set of explicit unsigned types that you can use. These include UInt8, UInt16, UInt32 and UInt64. While you cannot represent negative values with these the extra 1-bit lets you represent values that are twice as big as their signed counterparts.

Here is a summary of the different integer types and their storage characteristics. Most of the time you will just want to use an Int. These become useful if your code is interacting with another piece of software that uses one of these more exact sizes

or if you need to optimize for storage size.

You’ve been using Double to represent fractional numbers. Swift offers a Float type which has less range and precision than Double but requires half as much storage. Modern hardware has been optimized for Double so it is the one that you should reach for unless you have good reason not to.

Most of the time you will just use Int and Double to represent numbers but every once in a while you might encounter the other types. You already know how to deal with them. For example, suppose you need to add together an Int16 with a UInt8 and an Int32. You can do that like so:

let a: Int16 = 12 let b: UInt8 = 255

let c: Int32 = -100000

let answer = Int(a) + Int(b) + Int(c) // answer is an Int

results matching ""

    No results matching ""