All lessons

Numbers & Math

6 min · Swift

Do math with variables and the basic operators.

Swift · Numbers & Math0/5 cleared

Enemy 1 of 5

This code stores a price and a quantity in variables, then prints them multiplied together. Press Run to see 15. Remember that dividing two Int values drops the remainder.

Why this works

Swift supports the same familiar arithmetic operators you'd expect: + for addition, - for subtraction, * for multiplication, and / for division. You can compute directly on literal numbers, but in real code it's far more common to store values in variables first (since they usually come from user input or an earlier step) and then combine the variables.

To print a calculation, just place the expression inside print's parentheses: print(price * quantity). Swift evaluates the multiplication first, then prints the resulting value. There's no special formatting syntax required, unlike Rust's {} placeholders.

One gotcha worth knowing up front: dividing two Int values with / performs integer division and drops any remainder, so 7 / 2 evaluates to 3, not 3.5. To get a fractional result, at least one side needs to be a Double: 7.0 / 2 gives 3.5. This behavior (shared with Rust, Kotlin, Java, and C) trips up nearly everyone the first time they encounter it, so it's worth remembering rather than debugging from scratch each time.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.