Integers are whole numbers that can be negative, zero, or positive and cannot have a fractional component. In programming, zero and positive integers are termed as “unsigned”, and the negative ones are “signed”. Swift provides these two categories in the form of 8-bit, 16-bit, 32-bit and 64-bit format. The integers in Swift follow a naming convention similar to C, i.e., a signed 16-bit integer is of type “Int16”, and an unsigned 8-bit integer is of type “UInt8”.
Integer Bounds
Integer Type | Min | Max |
---|---|---|
UInt8 | 0 | 255 |
UInt16 | 0 | 65535 |
UInt32 | 0 | 4294967295 |
UInt64 | 0 | 18446744073709551615 |
Int8 | -128 | 127 |
Int16 | -32768 | 32767 |
Int32 | -2147483648 | 2147483647 |
Int64 | -9223372036854775808 | 9223372036854775807 |
Int: Swift provides an additional integer type, “Int”, which does not require the user to explicitly mention any of the above integer types unless restrictions are imposed.
UInt: Similarly, Swift also provides “UInt”, which also can be used unless any specific type is required.
Note: Both “Int” and “UInt” are platform native. This means, if the platform where the code is run is a 32-bit platform, then “Int” will be the same as “Int32”, and “UInt” will be the same as “UInt 32”. The same is the case with a 64-bit platform.
Additionally, we can run a program in Swift to find the minimum and maximum values of the integer type using the “min” and “max” functions, the corresponding outputs are as follows:
Illustration:
print("Integer Type Min Max") print("UInt8 \(UInt8.min) \(UInt8.max)") print("UInt16 \(UInt16.min) \(UInt16.max)") print("UInt32 \(UInt32.min) \(UInt32.max)") print("UInt64 \(UInt64.min) \(UInt64.max)") print("Int8 \(Int8.min) \(Int8.max)") print("Int16 \(Int16.min) \(Int16.max)") print("Int32 \(Int32.min) \(Int32.max)") print("Int64 \(Int64.min) \(Int64.max)")
Output:
Integer Type Min Max UInt8 0 255 UInt16 0 65535 UInt32 0 4294967295 UInt64 0 18446744073709551615 Int8 -128 127 Int16 -32768 32767 Int32 -2147483648 2147483647 Int64 -9223372036854775808 9223372036854775807
Now dwelling on the next numbers, Floating-Point Numbers are the numbers that can represent a fractional component. These can also represent integers in a decimal form. Swift provides two signed types of these numbers:
Type | N-bit floating-point number | Number of decimal places |
---|---|---|
Double | 64-bit floating-point number | 15 |
Float | 32-bit floating-point number | 6 |
Examples:
6.89, 3.1466, 6778.0, 0.0, 445.99