Swift Int Examples: Int.max, Int.minUse the Int type and the Int.max and Int.min properties. Test Ints with MemoryLayout.
dot net perls
Int. Numbers are used throughout Swift programs. With an Int, we have an integral type that can be used in expressions, collections and loops.
Int is important. 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, 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.
// Display byte size of Int.
Swift program that shows Int usage
let size = MemoryLayout<Int>
// Display maximum Integer value.
let max = Int.max
// Display minimum Integer value.
let min = Int.min
// Use advanced to increment an Int.
var value = 100
let result = value.advanced
// Use advanced to move forward and back.
let next = result.advanced
let previous = result.advanced
In an overflow, a number cannot be represented using the available bits. This causes a logic problem and unexpected results.
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.
// Part 1: do a multiply that overflows.
Swift program that uses multiplyWithOverflow
let res1 = Int.multiplyWithOverflow
// Test whether it overflowed.
print("An overflow happened"
// Part 2: do a multiply that will not overflow.
let res2 = Int.multiplyWithOverflow
// We did not have an overflow, so print the 0 value.
An overflow happened
By default in Swift an overflow causes an error. With the overflow add, subtract and multiply operators, this error does not appear.
Instead The numeric value will become invalid. It will wrap around to the lowest (or highest) value.
// This number cannot be incremented without overflow.
Swift program that uses overflow add operator
var number = Int8.max
// Use overflow operator to avoid an error.
// ... Add 1 to number.
number = number &+
&+ Overflow addition
&- Overflow subtraction
&* Overflow multiplication
Convert to 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.
Numbers are everywhere. Int is used in nearly every program. It is 8 bytes, which makes it similar to "long" values in other languages.
© 2007-2021 sam allen. send bug reports to email@example.com.