Numbers & Math
6 min · Swift
Do math with variables and the basic operators.
Enemy 1 of 5
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.
Loading editor...