Swift - Data Type Integers

Introduction

Integers are whole numbers with no fractional parts.

Integers can be positive or negative.

In Swift, integers are represented using the Int type.

The Int type represents both positive as well as negative values.

If you only need to store positive values, you can use the unsigned integer UInt type.

The size of an Int type depends on the system on which your code is running.

On 32-bit systems, Int and UInt each use 32 bits for storage, whereas on 64-bit systems Int and UInt each use 64 bits.

You can programmatically check the number of bytes stored by each data type using the sizeof() function:

print("Size of Int: \(sizeof(Int)) bytes")
print("Size of UInt: \(sizeof(UInt)) bytes")

If you run the preceding statement on an iPhone 5 which uses the 32-bit A6 chip, you will get the following:

Size of Int: 4 bytes
Size of UInt: 4 bytes

If you run the preceding statement on an iPhone 5s which uses the 64-bit A7 chip, you will get the following:

Size of Int: 8 bytes
Size of UInt: 8 bytes

If you do not know the type of data a variable is storing, you can use the sizeofValue() function:

Demo

var num = 5
print("Size of num: \(sizeofValue(num)) bytes")

Related Topics

Exercise