Search⌘ K
AI Features

Operators and Expressions

Explore Swift operators and expressions to manipulate data effectively. Learn about arithmetic, comparison, Boolean logic, compound assignments, ternary and nil coalescing operators to control program flow and evaluate conditions in your Swift code.

So far, we have looked at using variables and constants in Swift and also described the different data types. Being able to create variables, however, is only part of the story. The next step is to learn how to use these variables and constants in Swift code. The primary method for working with data is in the form of expressions.

Expression syntax in Swift

The most basic Swift expression consists of an operator, two operands, and an assignment. The following is an example of an expression:

var myresult = 1 + 2

In the above example, the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to a variable named myresult. The operands could just have easily been variables (or a mixture of constants and variables) instead of the actual numerical values used in the example.

C++
var myresult = 1 + 2
print(myresult)

In the remainder of this lesson, we will look at the basic types of operators available in Swift.

The basic assignment operator

We have already looked at the most basic of assignment operators, which is the = operator. This assignment operator simply assigns the result of an expression to a variable or constant. In essence, the = assignment operator takes two operands. The left-hand operand is the variable or constant to which a value is to be assigned, and the right-hand operand is the value to be assigned. The right-hand operand is more often than not an expression that performs some type of arithmetic or logical evaluation. The result of which will be assigned to the variable or constant. The following examples are all valid uses of the assignment operator:

C++
var x: Int? // Declare an optional Int variable
var y = 10 // Declare and initialize a second Int variable
x = 10 // Assign a value to x
print("x = \(x!)")
x = x! + y // Assign the result of x + y to x
print("x = \(x!)")
x = y // Assign the value of y to x
print("x = \(x!)")

Swift arithmetic operators

Swift provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators because they take two operands. The exception is the unary negative operator (-), which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-), which takes two operands (i.e., one value to be subtracted from another). For example:

var x = -10 // Unary - operator used to assign -10 to variable x
x = x - 5 // Subtraction operator. Subtracts 5 from x

The following table lists the primary Swift arithmetic operators:

Operator Description
-(unary) Negates the value of a variable or expression
* Multiplication
/ Division
+ Addition
- Subtraction
% Remainder/Modulo

Note that you can use multiple operators in a single expression. Operator precedence (the order in which the expression is evaluated) may, of course, be changed by placing sub-expressions in parentheses (()):

C++
let y = 20
let z = 35
var x = y * 10 + z - 5 / 4
print("x = \(x)")
x = y * (10 + z) - 5 / 4 // Add z to 10 first
print("x = \(x)")

Compound assignment operators

In an earlier section, we looked at the assignment operator (=). Swift provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, you might write an expression as follows:

C++
var x = 10
let y = 20
x = x + y
print("x = \(x)")

The above expression adds the value contained in variable x to the value contained in variable y, and stores the result in variable x. This can be simplified using the addition compound assignment operator (+=):

C++
var x = 10
let y = 20
x += y
print("x = \(x)")

The above expression performs exactly the same task as x = x + y but saves you some typing.

Numerous compound assignment operators are available in Swift, which is the most frequently used. These are outlined in the following table:

Operator Description
x += y Add x to y and place result in x
x -= y Subtract y from x and place result in x
x *= y Multiply x by y and place result in x
x /= y Divide x by y and place result in x
x %= y Perform Modulo on x and y and place result in x

Note: Swift does not include the unary increment and decrement operations (i.e., i++, ++i, --i, and i--) available in many other languages. The closest equivalent in Swift are += and -= operators (i.e., i += 1).

Comparison operators

Swift also includes a set of logical operators useful for performing comparisons. These operators all return a Boolean result depending on the result of the comparison. These operators are binary because they work with two operands.

Comparison operators are most frequently used in constructing program flow control logic. For example, an if statement may be constructed based on whether one value matches another:

if x == y {
      // Perform task
}

The result of the comparison may also be stored in a Bool variable. For example, the following code will result in a true value being stored in the variable named result:

C++
var result: Bool?
var x = 10
var y = 20
result = x < y
print("result = \(result!)")

Clearly, 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of Swift comparison operators:

Operator Description
x == y Returns true if x is equal to y
x > y Returns true if x is greater than y
x >= y Returns true if x is greater than or equal to y
x < y Returns true if x is less than y
x <= y Returns true if x is less than or equal to y
x != y Returns true if x is not equal to y

Boolean logical operators

Swift also provides a set of so-called logical operators designed to return Boolean true or false values. These operators both return Boolean results and take Boolean values as operands. The key operators are NOT (!), AND (&&), and OR (||). The NOT (!) operator simply inverts the current value of a Boolean variable or the result of an expression. For example, if a variable named flag is currently true, prefixing the variable with a ! character will invert the value to false:

var flag = true // variable is true
var secondFlag = !flag // secondFlag set to false

The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. For example, the following code evaluates to true because at least one of the expressions on either side of the OR operator is true:

C++
if (10 < 20) || (20 < 10) {
print("Expression is true")
}

The AND (&&) operator returns true only if both operands evaluate to be true. The following example will return false because only one of the two operand expressions evaluates to true:

C++
if (10 < 20) && (20 < 10) {
print("Expression is true")
} else {
print("Expression is false")
}

The ternary operator

Swift supports the ternary operator to provide a shortcut way of making decisions within code. The syntax of the ternary operator (also known as the conditional operator) is as follows:

condition ? true expression : false expression

The way the ternary operator works is that condition is replaced with an expression that will return either true or false. If the result is true, then the expression that replaces the true expression is evaluated. Conversely, if the result was false, then the false expression is evaluated. Let’s see this in action:

C++
let x = 10
let y = 20
print("Largest number is \(x > y ? x : y)")

The above code example will evaluate whether x is greater than y. Clearly, this will evaluate to false resulting in y being returned to the print call for display to the user.

Nil coalescing operator

The nil coalescing operator (??) allows a default value to be used in the event that an optional has a nil value. The following example will output text which reads “Welcome back, customer” because the customerName optional is set to nil:

C++
let customerName: String? = nil
print("Welcome back, \(customerName ?? "customer")")

On the other hand, if customerName is not nil, the optional will be unwrapped and the assigned value displays:

C++
let customerName: String? = "John"
print("Welcome back, \(customerName ?? "customer")")

On execution, the print statement output will now read “Welcome back, John.”

Lesson recap

  • Swift expressions are comprised of operands and operators.

  • Swift includes a range of arithmetic, comparison, and boolean logical operators.

  • Compound assignment operators allow basic arithmetic assignment expressions to be simplified.

  • The ternary operator provides a terse way to decide what action to take based on whether an expression evaluates to true or false.

  • The nil coalescing operator allows a default value to be used in the event that an optional has a nil value

Quiz

Test your knowledge of Swift operators and expressions by completing this quiz.

Technical Quiz
1.

Which of the following makes use of a compound assignment operator?

A.
y = x++
B.
y = x + y
C.
x += y

1 / 2

Exercises

Use these exercises to strengthen your understanding of Swift operators and expressions.

Exercise 1

Use a ternary operator to identify whether constant x is odd or even.

Exercise
Solution
let x = 11

Exercise 2

Write an if statement that uses the logical AND operator to identify if x is even and less than 100.

Exercise
Solution
let x = 10