Swift - Data Type Integer Literals

Introduction

You can represent integer values as follows:

  • Binary-Use the 0b prefix.
  • Octal-Use the 0o prefix.
  • Hexadecimal-Use the 0x prefix.

The following code snippet shows the number 15 represented in the four forms:

let num1 = 15      //decimal
let num2 = 0b 1111 //binary
let num3 = 0o 17   //octal
let num4 = 0x F    //hexadecimal

You can pad the integers with zeros if you want to make them more readable.

The preceding code snippet can be rewritten as the following statements without changing the value represented:

let num1 = 000000 15       //decimal
let num2 = 0b 00 1111       //binary
let num3 = 0o 0000 17       //octal
let num4 = 0x 00000 F       //hexadecimal

For big numbers, you can also use underscores _ to make them more readable.

For example, instead of writing one billion as:

let billion = 1000000000

you can use the underscore to make it more readable:

let billion = 1_000_000_000

The following represents the same value as the previous statement:

let billion = 100_00_00_00_0

Related Topic