Integers

Integers are numbers without a fractional part. They are either signed (positive, zero, or negative) or unsigned (positive or zero).

Signed integer types which check for overflow and underflow have an Int prefix and can represent values in the following ranges:

  • Int8: −2^7 through 2^7 − 1 (-128 through 127)

  • Int16: −2^15 through 2^15 − 1 (-32768 through 32767)

  • Int32: −2^31 through 2^31 − 1 (-2147483648 through 2147483647)

  • Int64: −2^63 through 2^63 − 1 (-9223372036854775808 through 9223372036854775807)

  • Int128: −2^127 through 2^127 − 1

  • Int256: −2^255 through 2^255 − 1

Unsigned integer types which check for overflow and underflow have a UInt prefix and can represent values in the following ranges:

  • UInt8: 0 through 2^8 − 1 (255)

  • UInt16: 0 through 2^16 − 1 (65535)

  • UInt32: 0 through 2^32 − 1 (4294967295)

  • UInt64: 0 through 2^64 − 1 (18446744073709551615)

  • UInt128: 0 through 2^128 − 1

  • UInt256: 0 through 2^256 − 1

Unsigned integer types which do not check for overflow and underflow, i.e. wrap around, have the Word prefix and can represent values in the following ranges:

  • Word8: 0 through 2^8 − 1 (255)

  • Word16: 0 through 2^16 − 1 (65535)

  • Word32: 0 through 2^32 − 1 (4294967295)

  • Word64: 0 through 2^64 − 1 (18446744073709551615)

The types are independent types, i.e. not subtypes of each other.

See the section about arithmetic operators for further information about the behavior of the different integer types.

// Declare a constant that has type `UInt8` and the value 10.
let smallNumber: UInt8 = 10
// Invalid: negative literal cannot be used as an unsigned integer
//
let invalidNumber: UInt8 = -10

In addition, the arbitrary precision integer type Int is provided.

let veryLargeNumber: Int = 10000000000000000000000000000000

Integer literals are inferred to have type Int, or if the literal occurs in a position that expects an explicit type, e.g. in a variable declaration with an explicit type annotation.

let someNumber = 123

// `someNumber` has type `Int`

Negative integers are encoded in two's complement representation.

Integer types are not converted automatically. Types must be explicitly converted, which can be done by calling the constructor of the type with the integer type.

let x: Int8 = 1
let y: Int16 = 2

// Invalid: the types of the operands, `Int8` and `Int16` are incompatible.
let z = x + y

// Explicitly convert `x` from `Int8` to `Int16`.
let a = Int16(x) + y

// `a` has type `Int16`

// Invalid: The integer literal is expected to be of type `UInt8`,
// but the large integer literal does not fit in the range of `UInt8`.
//
let b = x + 1000000000000000000000000

Last updated