C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Max, min: These are useful properties on the Int. As we see in the output, an Int in Swift is like a long in other languages.
Advanced: This adds to the Int. We can just use an add operator like "+=" for most programs.
Tip: To go to the previous number, we can use advanced() by negative one. But subtracting one is likely clearer.
Swift program that shows Int usage
// 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)
Output
8
9223372036854775807
-9223372036854775808
110
111
109
Part 1: We try to capture overflows with multiplyWithOverflow. We perform a multiply that causes an overflow.
Part 2: Here the numbers multiplied do not overflow, so the "overflow" property returns false.
Tip: Other methods include addWithOverflow, divideWithOverflow, remainderWithOverflow and subtractWithOverflow.
Swift program that uses multiplyWithOverflow
// Part 1: do a multiply that overflows.
let res1 = Int.multiplyWithOverflow(Int.max, 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 = Int.multiplyWithOverflow(2, 2)
print(res2)
// We did not have an overflow, so print the 0 value.
if !res2.overflow {
print(res2.0)
}
Output
(-2, true)
An overflow happened
(4, false)
4
Instead: The numeric value will become invalid. It will wrap around to the lowest (or highest) value.
Swift program that uses overflow add operator
// 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)
Output
127
-128
Operators:
&+ Overflow addition
&- Overflow subtraction
&* Overflow multiplication
Quote: For both signed and unsigned integers, overflow in the positive direction wraps around from the maximum valid integer value back to the minimum, and overflow in the negative direction wraps around from the minimum value to the maximum.
Advanced Operators: apple.com