Int
Numbers are used throughout Swift programs. With an Int
, we have an integral type that can be used in expressions, collections and loops.
In Swift we find it is 8 bytes and can accommodate large numbers. It does not support fractional values. We can handle overflow with special methods.
Let us run through some Int
properties. First we use MemoryLayout
on the Int
type. This returns the byte
count in an Int
which is 8.
Max
and min are useful properties on the Int
. As we see in the output, an Int
in Swift is like a long in other languages.Advanced()
adds to the Int
. We can just use an add operator like "+=" for most programs.advanced()
by negative one. But subtracting one is likely clearer.// Display byte size of Int. let size = MemoryLayout<Int>.size print(size) // Display maximum Integer value. let max = Int.max print(max) // Display minimum Integer value. let min = Int.min print(min) // Use advanced to increment an Int. var value = 100 let result = value.advanced(by: 10) print(result) // Use advanced to move forward and back. let next = result.advanced(by: 1) print(next) let previous = result.advanced(by: -1) print(previous)8 9223372036854775807 -9223372036854775808 110 111 109
ReportingOverflow
In an overflow, a number cannot be represented using the available bits. This causes a logic problem and unexpected results.
multipliedReportingOverflow
. We perform a multiply that causes an overflow.multipliedReportingOverflow
.// Part 1: do a multiply that overflows. let res1 = Int.max.multipliedReportingOverflow(by: 2) print(res1) // Test whether it overflowed. if res1.overflow { print("An overflow happened") } // Part 2: do a multiply that will not overflow. let res2 = 2.multipliedReportingOverflow(by: 2) print(res2) // We did not have an overflow, so print the 0 value. if !res2.overflow { print(res2.0) }(partialValue: -2, overflow: true) An overflow happened (partialValue: 4, overflow: false) 4
By default in Swift an overflow causes an error. With the overflow add, subtract and multiply operators, this error does not appear.
// This number cannot be incremented without overflow. var number = Int8.max print(number) // Use overflow operator to avoid an error. // ... Add 1 to number. number = number &+ 1 print(number)127 -128&+ Overflow addition &- Overflow subtraction &* Overflow multiplication
String
With the String
init
method, we can convert an Int
into a String
. This always succeeds. Every possible Int
can be represented as a String
.
Int
is used in nearly every program. It is 8 bytes, which makes it similar to "long" values in other languages.