Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 146 ยท Getting Started

Operators

Learn every everyday Swift operator - arithmetic, remainder, comparison, logical, nil-coalescing, ternary, range and compound assignment - plus precedence and a preview of custom operators.

An operator is a short symbol that combines or transforms values: +, ==, &&, ??. Swift's operators look familiar if you have used C, Java or JavaScript, but they are stricter in useful ways. Arithmetic overflow is caught instead of silently wrapping, comparisons must produce a Bool, there is no ++, and operators are ordinary functions from the standard library, which means you can define new ones.

This lesson tours the operators you will use every day, explains precedence (which one binds first), and previews custom operators. It follows Basic Types and Working with Numbers, and it prepares you for conditions in if and else.

Terminology: unary, binary, ternary

A unary operator has one operand: -x (prefix) or value! (postfix). A binary operator sits between two operands: a + b. The ternary operator ?: has three, and Swift has exactly one of those. Swift's convention is spaces on both sides of a binary operator and none between a unary operator and its operand.

Arithmetic

The four basic operators are +, -, * and /, and % is the remainder. Both operands must have the same type, as you saw in Basic Types.

Swift Arithmetic and division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Dividing two integers gives an integer, so 7 / 3 is 2. To get 2.333... at least one side must be a floating-point value. The % operator works only on integers and keeps the sign of the left operand: -7 % 3 is -1, not 2. If you want a result that is never negative (for wrapping an index around an array), you need an extra step such as ((a % n) + n) % n. For floating point use truncatingRemainder(dividingBy:). Also notice that + is overloaded: it adds numbers, joins strings and concatenates arrays.

Two things that exist in other languages do not exist in Swift. There is no exponent operator (2 ** 8 or 2 ^ 8 do not mean power; use pow from Foundation for floating point or a loop, see Working with Numbers), and there is no ++ or --; write count += 1.

Overflow is a trap

When an integer result does not fit its type, Swift stops the program instead of silently wrapping around:

Swift Arithmetic overflow traps (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program crashes with a trap: the runner reports Illegal instruction (signal 4) and no message. The Largest Int: line that was printed first still appears, because the runner flushes output line by line. If wrapping is exactly what you want, say so with the overflow operators &+, &- and &*, or ask whether it overflowed:

Swift Wrapping operators and overflow reporting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The & versions never trap; they keep the low bits. addingReportingOverflow gives you both the wrapped value and a flag. Wrapping arithmetic is the right tool for hashes, checksums and random generators, and the wrong tool for ordinary sums, where a trap is better than a wrong answer.

Compound assignment

Every arithmetic operator has an assignment form: +=, -=, *=, /=, %=. They modify a var in place. Assignment itself (=) does not return a value in Swift, so if x = 5 is an error, and the common typo of = for == cannot compile.

Swift Compound assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Following the steps: 10 becomes 15, 12, 24, 6 and finally 6 % 4 = 2. Compound assignment works for strings and arrays too, because + is defined for them.

Comparison

==, !=, <, <=, >, >= compare values and return a Bool. They work on numbers, strings, characters, and any type that conforms to Equatable or Comparable (Equatable, Hashable and Comparable). Tuples of up to six comparable elements compare lexicographically, element by element, which is a handy way to sort by several keys.

Swift Comparison operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The tuple comparison looks at the first elements and moves on to the second only if they are equal. === and !== are identity operators for class instances: they ask "is this the very same object?", unlike ==, which asks "are these equal?". They matter once you meet classes in Classes.

Comparing values of different types does not compile, and chained comparison like 1 < x < 10 is not allowed either, which leads us to the compiler messages.

Swift Chained comparison is not allowed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: adjacent operators are in non-associative precedence group 'ComparisonPrecedence' (followed by a second, consequential type error). Write 1 < x && x < 10, or better, use a range: (1...10).contains(x) or 1...10 ~= x.

Logical operators

&& (and), || (or) and ! (not) work only on Bool. Both && and || are short-circuit operators: the right side is evaluated only if the left side has not already decided the result. That is used constantly to guard a risky operation:

Swift Short-circuit evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

For && the right operand never ran, because false && anything is false. The same goes for || after a true. The final test is safe on an empty array because isEmpty is checked first; swapping the two operands would crash. Precedence between them: && binds tighter than ||, so a || b && c means a || (b && c). Add parentheses when mixing them, because readers do not remember tables.

Nil-coalescing: ??

The ?? operator takes an optional on the left and a default on the right. It yields the wrapped value if there is one, and the default otherwise. The right side is an autoclosure, so it is only evaluated when needed. You met it when parsing input in Reading Input.

Swift Providing defaults with ??

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The default for stored is never computed (no "computing default" line for the first call), and ?? chains from left to right, which is useful for a list of fallbacks. Optionals themselves are explained in Optionals.

The ternary conditional

condition ? valueIfTrue : valueIfFalse is an expression that picks one of two values. It is best for short, simple choices:

Swift The ternary operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two branches must have the same type. Nesting works, as in advice, but a second ?: is already hard to read; from there on an if or switch expression (if and else, switch) is clearer.

Range operators

Swift has compact syntax for ranges of values. a...b is a closed range that includes both ends, a..<b is half-open and excludes b (the natural fit for array indices), and ...b, a... and ..<b are one-sided ranges.

Swift Range operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A closed range cannot be empty and a half-open range can (3..<3). A range with a lower bound greater than the upper bound traps at runtime. Ranges covers everything, including stride for steps other than one.

Other operators worth knowing

  • Bitwise: &, |, ^, ~, <<, >> work on integers. Shifts on integers are "smart": shifting by more bits than the width gives 0 and not undefined behavior.
  • Pattern match ~=: 1...10 ~= x tests whether x falls in the range; it is what switch uses under the hood (Pattern Matching).
  • Optional chaining and force unwrap: value?.property and value!.
  • Type operators: is, as, as?, as! (Type Casting).
  • Nil-check: x == nil and x != nil work for any optional.

Precedence and associativity

When an expression has several operators, precedence decides which is applied first and associativity decides the order among equals. Multiplication binds tighter than addition, comparison comes after arithmetic, && after comparison, then ||, then the ternary, then assignment. Parentheses always win.

Swift Precedence in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

10 - 4 - 3 is (10 - 4) - 3 = 3 because subtraction is left-associative. The shift in 1 + 2 << 1 is evaluated first (2 << 1 is 4), so the result is 5, which surprises people coming from C where shift binds weaker than addition. When you need to look up precedence to read your own line, add parentheses instead.

Custom operators (a preview)

An operator is an ordinary function with a special name, and you can overload existing operators for your own types or declare new ones. Overloading is common (that is how Vector + Vector works); inventing new symbols is rare and should be done carefully, because unfamiliar symbols make code harder to read.

Swift Overloading and declaring operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first three are overloads, which need no declaration. The ** operator is brand new, so it needs infix operator **: MultiplicationPrecedence, which says where it sits in the precedence table. Inventing symbols like this is exactly what style guides warn about, so treat it as an exercise and not a recommendation. Operator functions for your own types should also conform them to protocols such as Equatable, which is covered in Equatable, Hashable and Comparable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -7 % 3 evaluate to in Swift?

    The remainder operator takes the sign of the left operand: -7 = (-2 * 3) + (-1), so the result is -1.
  2. 2. What happens when Int.max + 1 is evaluated with the normal + operator?

    Swift checks integer overflow and stops the program. Use &+ for wrapping or addingReportingOverflow to detect it.
  3. 3. Which expression gives a default of 0 when count is an Int? that may be nil?

    ?? is the nil-coalescing operator: it yields the wrapped value or the default.
  4. 4. Why is the code 1 < x < 10 rejected by the compiler?

    Swift reports that adjacent operators are non-associative. Write 1 < x && x < 10 or 1...10 ~= x.
  5. 5. In a || b && c, which part is evaluated as a group first?

    && has higher precedence than ||, so the expression means a || (b && c). Use parentheses to make that visible.

Summary

  • Swift has + - * / %, comparison, && || !, bitwise, range, ?? and ?:; there is no ++, -- or power operator.
  • Integer / drops the fraction and % keeps the left operand's sign; mixing Int and Double needs a conversion.
  • Overflow traps by default; &+, &-, &* and the ...ReportingOverflow methods are the explicit alternatives.
  • && and || short-circuit; ?? is lazy on its right side; === compares class identity.
  • Range operators ..., ..< and their one-sided forms are used for loops, slicing and switch.
  • Precedence follows math rules; use parentheses whenever it helps. You can overload operators for your types and declare new ones, sparingly.

Next: if and else