Operations on Integers

Swift allows you to perform basic mathematical operations on integers using the familiar operators + (add), - (subtract), and * (multiply). Try printing the results of some arithmetic.

Listing 4.8  Performing basic operations

...
let numberOfPeople: UInt = 40
let volumeAdjustment: Int32 = -1000

print(10 + 20)
print(30 - 5)
print(5 * 6)

The compiler respects the mathematical principles of precedence and associativity, which define the order of operations when there are multiple operators in a single expression. For example:

Listing 4.9  Order of operations

...
print(10 + 20)
print(30 - 5)
print(5 * 6)

print(10 + 2 * 5) // 20, because 2 * 5 is evaluated first
print(30 - 5 - 5) // 20, because 30 ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.