What are Int8, Int16, Int32 and Int64?
Int8, Int16, Int32 and Int64 are integer types with a fixed size. The number in the name is how many bits each value gets, and that decides how big a number it can hold.
Size and range#
More bits means a bigger range, but more memory too.
| Type | Size | Range (approx.) |
|---|---|---|
Int8 | 1 byte | −128 to 127 |
Int16 | 2 bytes | −32,768 to 32,767 |
Int32 | 4 bytes | about ±2.1 billion |
Int64 | 8 bytes | about ±9.2 quintillion |
Signed and unsigned#
Each size comes in two forms. A signed type like Int32 can hold negative numbers. An unsigned type like UInt32 can’t, so its whole range shifts up: 0 through about 4.29 billion.
In Swift#
let count = 42 // Int (64-bit on iOS)Int.max // 9,223,372,036,854,775,807Int32.max // 2,147,483,647UInt8.max // 255In Swift, the default Int is 64-bit on every current iPhone and Mac, and Apple recommends using it for everyday tasks.
Which one to use#
We should avoid unsigned types, even for non-negative values, because the app can end up crashing if the value goes negative:
func remaining(after used: UInt, of total: UInt) -> UInt { total - used}remaining(after: 3, of: 10) // 7remaining(after: 12, of: 10) // Crashes: arithmetic overflowYouTube’s 32-bit view counter was maxed out by Gangnam Style. YouTube now uses a 64-bit counter, which can count up to about 9.22 quintillion views. If a value can grow without limit, start with 64 bits.