Skip to main content

All about Numeric Literals in Swift

·3 mins

All about Numeric Literals in Swift #

Integers and Floating Points are two basic numeric data types in Swift. Integers are whole numbers with no fractional component in it, such as 27 and -89. Integers are either signed (positive, negative and zero) or unsigned (positive and zero). On the other hand, Floating-point number are numbers with a fractional component, such as 3.14159 and -676.89.

Swift provides integers in following forms #

Signed Integers

Int // 32 bit in a 32-bit platform and 64 bit in a 64-bit platform
Int8 // signed 8-bit integer 
Int16
Int32
Int64

Unsigned Integers

UInt // 32 bit in a 32-bit platform and 64 bit in a 64-bit platform
UInt8 // unsigned 8-bit integer 
UInt16
UInt32
UInt64

Swift provides two signed floating-points in following forms #

Double // 64-bit floating-point number
Float // 32-bit floating-point number

On a 32 bit platform, Int is the same size as Int32 and on a 64-bit platform, Int is the same size as Int64, In case of UInt, it is similar as well. You should always use Int for integer values whenever possible as it aids code consistency and interoperability across all platforms.

You can access the minimum and maximum values of each integer type with its min and max properties:

let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8

Whenever constant and variable type is not explicitly specified, Int is infered as data type from integer literals and Double is inferred as data type from floating-point literals.

let maxNumberOfParticipants = 10 // is same as let maxNumberOfParticipants: Int = 10
let pi = 3.14159 // is same as let pi: Double = 3.14159

Integer literals can be written as a decimal number with no prefix and binary/octal/hexadecimal numbers with 0b / 0o / 0x prefix respectively.

let decimalInteger = 17           // 17 in decimal notation
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

Floating-point literals can be written as decimal with no prefix or hexadecimal with 0x prefix. Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase e; hexadecimal floats must have an exponent, indicated by an uppercase or lowercase p.

let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0

Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeros and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal:

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1