Basics: Numeric Type Conversion

Use the Int type for all general-purpose integer constants and variables in your code, even if they’re known to be nonnegative.

Use other integer types only when they’re specifically needed for the task at hand, because of explicitly sized data from an external source, or for performance, memory usage, or other necessary optimization.

Integer Conversion

The range of numbers that can be stored in an integer constant or variable is different for each numeric type.

Let cannotBeNegative: UInt8 = -1
// UInt8 cannot store negative numbers, and so this will report an error
let tooBig: Int8 = Int8.max + 1
// Int8 cannot store a number larger than its maximum value,
// and so this will also report an error
Let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)

Additional information

  • A number that won’t fit into a constant or variable of a sized integer type is reported as an error when your code is compiled.
  • To convert one specific number type to another, you initialize a new number of the desired type with the existing value.

Integer and Floating-Point Conversion

Let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double
Let integerPi = Int(pi)
// integerPi equals 3, and is inferred to be of type Int

Additional information

  • Conversions between integer and floating-point numeric types must be made explicit.
  • Floating-point to integer conversion must also be made explicit.

Basics: Numeric Type Conversion — Structure map

Clickable & Draggable!

Basics: Numeric Type Conversion — Related pages: