Basic Operators in Swift

Harshvardhan Arora
1 min readMar 1, 2022

The entire playground used in the article can be found here!

Terminology

Unary Operators — Operate on Single Target. Can be prefix (!a) or postfix (a!)
Binary Operators — Operate on Two Targets. Can only be infix (a + b)
Ternary Operators — Operate on Three Targets. Only one in Swift — (a ? b : c)

Assignment Operator

(x, y) is a compound type called Tuple. Will be discussed in later tutorials.

Arithmetic Operators

Remainder Operator

Unary Minus Operator

Unary Plus Operator

Compound Assignment Operators

Comparison Operators

Ternary Conditional Operator

question ? answerIfTrue : answerIfFalse
The type of answerIfTrue and answerIfFalse should be the same as the expected return type.

Nil-Coalescing Operator

a ?? b — Unwraps an optional a if it contains a value or returns b.
a should be an optional and b should not while matching the type of a.
Equivalent of a != nil ? a! ? b

Range Operators

For a…b (Closed Range) and a..<b (Open Range), a <= b

Logical Operators

--

--