Start learning free

LESSON 16 OF 415 · CALCULATIONS WITH NUMBERS

Arithmetic Operators in Swift: + - * / and %

Lesson Read the full explanation

TL ; DR:

  • We can tell computers to perform calculations for us using +, -, *, /:

    print(2 + 6) // Prints 8
    print(10 - 7) // Prints 3
    print(3 * 3) // Prints 9
    print(6 / 2) // Prints 3
    


  • We can also use variables. In these examples, Swift will replace variable num with its value 6 to do the calculations:

    let num = 6
    print(num + 5) // Prints 11
    print(10 - num) // Prints 4
    print(3 * num) // Prints 18
    print(num / 2) // Prints 3
    



Full lesson:

Computers absolutely excel at performing calculations. The "compute" in their name comes from their historical association with providing answers to mathematical questions.

These calculations can be performed either directly with numbers or with variables that are assigned numeric values.

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Examples
+ Addition 3 + 5,  x + 5,  3 + y,  x + y
- Subtraction 8 - 3,  8 - y,  x - 3,  x - y
* Multiplication 3 * 5,  3 * y,  x * 5,  x * y
/ Division 8 / 4,  8 / y,  x / 8,  x / y
% Modulus 8 % 4,   8 % y,  x % 4,  x % y


Note that performing arithmetic on variables does not change the variable - you can only update a variable using the = sign.

Let's go through some examples together to better understand how each operator works:


Addition

// Declare 2 integer variables and initialize them:
let a = 2
let b = 3

print(a + b) // Output: 5

print(a + 10) // Output: 12

Subtraction

// Declare 2 integer variables and initialize them:
let a = 2
let b = 3

print(a - b) // Output: -1

print(10 - b) // Output: 7

Multiplication

// Declare 2 integer variables and initialize them:
let a = 2
let b = 3

print(a * 5) // Output: 10

print(2 * a * b) // Output: 12

Division

In Swift, division between integers returns only the integral part of the result:

// Declare 2 integer variables and initialize them:
let a = 2
let b = 3

print(20 / 3) // Output: 6

print(b / a) // Output: 1

If we want to get the real result of the division, the values have to be of type Double (a plain number like 2 in Double(7) / 2 is read as a Double automatically):

// Declare 2 integer variables and initialize them:
let a = 2
let b = 3

print(Double(7) / 2) // Output: 3.5

print(Double(b) / Double(a)) // Output: 1.5

Assignment
Follow the Coding Tutorial and let's practice with arithmetic operators!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · CALCULATIONS WITH NUMBERS

    Arithmetic Operators in Swift, explained

    The operators

    Swift calculates with the usual operators. They work on numbers written directly in the code and on constants and variables that hold numbers.

    OperatorNameExampleResult
    +addition2 + 68
    -subtraction10 - 73
    *multiplication3 * 39
    /division6 / 23
    %remainder7 % 31

    With variables, Swift substitutes the stored values:

    let num = 6
    print(num + 5)
    print(10 - num)
    print(3 * num)
    print(num / 2)
    
    11
    4
    18
    3
    

    A calculation does not change the variables in it. num + 5 produces a new value and num is still 6. Only an assignment, such as num = num + 5, stores a result.

    Integer division

    When both operands are Int, / gives an Int and discards the fractional part. It truncates toward zero, so the result is not rounded:

    print(20 / 3)
    print(-7 / 2)
    print(7 % 3, -7 % 3)
    
    6
    -3
    1 -1
    

    The remainder % goes with integer division: 20 / 3 is 6 and 20 % 3 is 2, because 6 * 3 + 2 is 20. A nonzero remainder takes the sign of the left operand, so -7 % 3 is -1.

    For a fractional result, at least one side must be a Double. Swift does not mix Int and Double variables automatically, so convert one explicitly:

    let a = 2
    let b = 3
    print(Double(7) / 3)
    print(Double(b) / Double(a))
    print(7.0 / 2)
    
    2.3333333333333335
    1.5
    3.5
    

    Order of evaluation

    Multiplication, division and remainder bind tighter than addition and subtraction, as in school mathematics. Parentheses override that: 2 + 3 * 4 is 14, and (2 + 3) * 4 is 20.

    Updating a variable

    To store a result back in a var, combine the operator with =. Each of +=, -=, *=, /= and %= reads the variable, calculates and stores the result:

    var total = 4 * 83
    total += 15
    total *= 2
    total -= 1
    total /= 3
    total %= 100
    print(total)
    
    31
    

    Step by step, total goes 332, 347, 694, 693, 231 and finally 31. The remainder is useful for questions like how many items are left over: with 7 items and boxes of 3, 7 / 3 is 2 full boxes and 7 % 3 is 1 item left.

    The exercise

    The constant price holds the cost of one product, 83. Andy buys 4 of them and one bag for 15, and the program must print the total.

    1. The products cost 4 * price.
    2. The bag adds 15: 4 * price + 15.
    3. Multiplication is evaluated before addition, so no parentheses are needed.
    4. Put the whole expression inside print(...).

    The solution in Swift

    let price = 83
    print(4 * price + 15)
    

    It prints 347: 4 * 83 is 332, and 332 + 15 is 347.

    Swift details

    • Overflow is a run-time crash. An Int holds values up to 9223372036854775807. Adding 1 to that limit in an ordinary expression stops the program with an error, rather than wrapping around. The wrapping operators &+, &- and &* wrap on purpose: Int.max &+ 1 is -9223372036854775808.
    • Dividing an integer by zero also crashes. 10 / zero with let zero = 0 stops the program. With a Double zero, the result is inf instead.
    • Double arithmetic is approximate. 0.1 + 0.2 prints 0.30000000000000004.
    • Both sides need the same type. Int * Double is a compile error, so convert with Double(...).

    Common mistakes

    • Expecting 7 / 2 to be 3.5. With integers it is 3. Use 7.0 / 2.
    • Adding parentheses that change the meaning. 4 * (price + 15) is 392, not 347.
    • Forgetting print. The expression is calculated, but nothing is shown.
    • Hard-coding 83. Use price, so the result follows the constant.

    Key takeaways

    • + - * / % work on numbers, and *, / and % go before + and -.
    • Integer division truncates toward zero; use a Double operand for a fractional result.
    • A calculation produces a value and leaves its variables alone.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free