Integers in Swift

Swift Language

An integer (from the Latin integer meaning “whole”) is a number that can be written without a fractional component. For example, 3, 4, -7, and -1024 are integers, while 0.15, 1/2 , and √5 are not. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero).

Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C:

  • 8-bit unsigned integer is of type UInt8
  • 32-bit signed integer is of type Int32

Like all types in Swift, these integer types have capitalized names.

Int

In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size:

  • On a 32-bit platform, Int is the same size as Int32.
  • On a 64-bit platform, Int is the same size as Int64.

Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Intcan store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges.

UInt

Swift also provides an unsigned integer type, UInt, which has the same size as the current platform’s native word size:

  • On a 32-bit platform, UInt is the same size as UInt32.
  • On a 64-bit platform, UInt is the same size as UInt64.

Integer Bounds

In Swift, you can access the minimum and maximum values of each Integer type (8, 16, 32, and 64) with its min and max properties. Try the code below to Print the maximum and minimum values of UInt32:

let min = UInt32.min
let max = UInt32.max

Result:

  • min UInt32: 0
  • max UInt32: 4294967295
Print the maximum and minimum values of UInt32 in Swift
Print the maximum and minimum values of UInt32 in Swift

Converting Integers

1. Creates a new instance from the given integer

A value to convert to this type of integer. The value passed as source must be representable in this type.

Use this initializer to convert from another integer type when you know the value is within the bounds of this type. Passing a value that can’t be represented in this type results in a runtime error.

Example:

let x = 100
let y = Int8(x)
// y == 100
let z = Int8(x * 10)
// Error: Not enough bits to represent the given value

In the example, the constant y is successfully created from x, an Int instance with a value of 100. Because the Int8 type can represent 127 at maximum, the attempt to create z with a value of 1000 results in a runtime error.

2. Creates a new instance from the given integer, if it can be represented exactly

If the value passed as source is not representable exactly, the result is nil. In the following example, the constant x is successfully created from a value of 100, while the attempt to initialize the constant y from 1_000 fails because the Int8 type can represent 127 at maximum.

let x = Int8(exactly: 100)
// x == Optional(100)
let y = Int8(exactly: 1_000)
// y == nil

3. Creates a new instance with the representable value that’s closest to the given integer

If the value passed as source is greater than the maximum representable value in this type, the result is the type’s max value. If source is less than the smallest representable value in this type, the result is the type’s min value.

Example:

let x = Int8(clamping: 500)
// x == 127
// x == Int8.max

let y = UInt(clamping: -500)
// y == 0

In this example, x is initialized as an Int8 instance by clamping 500 to the range -128…127, and y is initialized as a UInt instance by clamping -500 to the range 0…UInt.max

4. Creates a new instance from the bit pattern of the given instance by truncating or sign-extending if needed to fit this type

When the bit width of T (the type of source) is equal to or greater than this type’s bit width, the result is the truncated least-significant bits of source. For example, when converting a 16-bit value to an 8-bit type, only the lower 8 bits of source are used.

let p: Int16 = -500
// 'p' has a binary representation of 11111110_00001100
let q = Int8(truncatingIfNeeded: p)
// q == 12
// 'q' has a binary representation of 00001100

When the bit width of T is less than this type’s bit width, the result is sign-extended to fill the remaining bits. That is, if source is negative, the result is padded with ones; otherwise, the result is padded with zeros.

let u: Int8 = 21
// 'u' has a binary representation of 00010101
let v = Int16(truncatingIfNeeded: u)
// v == 21
// 'v' has a binary representation of 00000000_00010101

let w: Int8 = -21
// 'w' has a binary representation of 11101011
let x = Int16(truncatingIfNeeded: w)
// x == -21
// 'x' has a binary representation of 11111111_11101011
let y = UInt16(truncatingIfNeeded: w)
// y == 65515
// 'y' has a binary representation of 11111111_11101011

Converting Floating-Point Values to Integer

1. Creates an integer from the given floating-point value, rounding toward zero

Any fractional part of the value passed as source is removed. A floating-point value to convert to an integer. source must be representable in this type after rounding toward zero.

let x = Int(21.5)
// x == 21
let y = Int(-21.5)
// y == -21

If source is outside the bounds of this type after rounding toward zero, a runtime error may occur.

let z = UInt(-21.5)
// Error: ...outside the representable range

2. Creates an integer from the given floating-point value, if it can be represented exactly

If the value passed as source is not representable exactly, the result is nil.

Example:

let x = Int(exactly: 21.0)
// x == Optional(21)
let y = Int(exactly: 21.5)
// y == nil

In the example, the constant x is successfully created from a value of 21.0, while the attempt to initialize the constant y from 21.5 fails.

Converting Strings to Integer

1. Creates a new integer value from the given string

The ASCII representation of a number. The string passed as description may begin with a plus or minus sign character (+ or -), followed by one or more numeric digits (0-9).

let x = Int("1234")
// x == 1234

If description is in an invalid format, or if the value it denotes in base 10 is not representable, the result is nil.

Int(" 100")                       // Includes whitespace
Int("21-50")                      // Invalid format
Int("ff6600")                     // Characters out of bounds
Int("10000000000000000000000000") // Out of range

2. Creates a new integer value from the given string and radix

The string passed as text may begin with a plus or minus sign character (+ or -), followed by one or more numeric digits (0-9) or letters (a-z or A-Z). Parsing of the string is case insensitive.

let x = Int("123")
// x == 123

let y = Int("-123", radix: 8)
// y == -83
let y = Int("+123", radix: 8)
// y == +83

let z = Int("07b", radix: 16)
// z == 123

If text is in an invalid format or contains characters that are out of bounds for the given radix, or if the value it denotes in the given radix is not representable, the result is nil. For example, the following conversions result in nil:

Int(" 100")                       // Includes whitespace
Int("21-50")                      // Invalid format
Int("ff6600")                     // Characters out of bounds
Int("zzzzzzzzzzzzz", radix: 36)   // Out of range

Creating a Random Integer

1. Returns a random value within the specified range

static func random(in: Range<Int>) -> Int

Use this method to generate an integer within a specific range. This example creates three new values in the range 1..<100.

for _ in 1...3 {
    print(Int.random(in: 1..<100))
}

2. Returns a random value within the specified range, using the given generator as a source for randomness

static func random<T>(in: Range<Int>, using: inout T) -> Int

Use this method to generate an integer within a specific range when you are using a custom random number generator. This example creates three new values in the range 1..<100.

for _ in 1...3 {
    print(Int.random(in: 1..<100, using: &myGenerator))
}

3. Returns a random value within the specified range.

static func random(in: ClosedRange<Int>) -> Int

Use this method to generate an integer within a specific range. This example creates three new values in the range 1…100.

for _ in 1...3 {
    print(Int.random(in: 1...100))
}

This method is equivalent to calling random(in:using:), passing in the system’s default random generator.

4. Returns a random value within the specified range, using the given generator as a source for randomness.

static func random<T>(in: ClosedRange<Int>, using: inout T) -> Int

Use this method to generate an integer within a specific range when you are using a custom random number generator. This example creates three new values in the range 1…100.

for _ in 1...3 {
    print(Int.random(in: 1...100, using: &myGenerator))
}