Menu
Coddy logo textTech

Compound Assignment

Part of the Fundamentals section of Coddy's Swift journey — lesson 18 of 86.

When you need to update a variable based on its current value, Swift provides compound assignment operators as a shorthand. Instead of writing the variable name twice, you can combine the arithmetic operation with the assignment in a single step.

var score = 10
score = score + 5  // The long way
score += 5         // The shorthand way

Both lines do the same thing — add 5 to score. The += operator reads as "add and assign."

Swift provides compound assignment operators for all basic arithmetic operations:

var number = 20

number += 5   // number is now 25
number -= 3   // number is now 22
number *= 2   // number is now 44
number /= 4   // number is now 11
number %= 3   // number is now 2

These operators are especially useful when you're tracking values that change over time, like keeping a running total or counting occurrences. They make your code shorter and easier to read.

challenge icon

Challenge

Easy

You are provided with the following variable:

var balance = 100

Perform the following operations on balance using compound assignment operators, in this exact order:

  1. Add 50 to balance
  2. Subtract 30 from balance
  3. Multiply balance by 2
  4. Divide balance by 4
  5. Get the remainder when dividing balance by 7

After all operations, print the final value of balance.

Cheat sheet

Swift provides compound assignment operators to update a variable based on its current value in a single step:

var score = 10
score += 5  // Add and assign (score is now 15)

Available compound assignment operators:

var number = 20

number += 5   // Add: number is now 25
number -= 3   // Subtract: number is now 22
number *= 2   // Multiply: number is now 44
number /= 4   // Divide: number is now 11
number %= 3   // Remainder: number is now 2

Try it yourself

var balance = 100

// TODO: Write your code below
// Use compound assignment operators to:
// 1. Add 50 to balance
// 2. Subtract 30 from balance
// 3. Multiply balance by 2
// 4. Divide balance by 4
// 5. Get the remainder when dividing balance by 7


// Print the final value of balance
print(balance)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals