Swift Tutorial 2 – How to Use Operators in Swift

Since we’ve discussed variables, the next logical step is to actually do something with those variables! In this section, we’re going cover the different types of operators supported by Swift.

Learn iOS by building real apps

Check out The Complete iOS Development Course – Build 14 Apps with Swift 2 on Zenva Academy to learn Swift 2 and iOS development from the ground-up with an expert trainer.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.

Assignment and Arithmetic

The most basic operator is the assignment operator. It simply sets the value of the left-hand side (LHS) to be the value of the right-hand side (RHS). We can even extend this to work with tuples. If the LHS is a tuple and the RHS is a tuple, tuple values on the LHS will be replaced by values on the RHS based on the ordering of the tuple: let (x, y) = (3, 7) . The value of x will be 3 because they are both in the 0th index of their respective tuples.

The next few operators are the basic arithmetic operators we’ve seen in mathematics. We have addition (+), subtraction (-), multiplication (*), and division (/). We can use the addition operator on numeric data types, but we can also use it as the string concatenation operator to combine two strings: var helloPlayground = “Hello, ” + “playground!” . The string concatenation operator will take the right argument and attach it to the end of the left argument. Note that we have to put a space in our strings since the operator does not automatically put a space in for us.

There’s one other operator called the remainder operator (%) that we can use to determine what value is left over from a division. For example, suppose we were dividing 26 and 4. Well 4 goes into 26 six times and leaves a remainder of 2: 4(6) + 2 = 26. The remainder operator would return 2 if we were doing 26 % 4 . While this may look similar to modulus, it is different from mathematical modulus. To see this, consider negative operands.

In addition to integer operands, we can also use it for floating point operands using the same formula. Suppose we were calculating 11 % 0.75 . Well 0.75 goes into 11 fourteen times and leaves a remainder of 0.5: 0.75(14) + 0.5 = 11. The remainder operator is most useful when checking the parity, or “evenness,” of a number. If we wanted to know if a number x is even, we can use the remainder operator and check if the result is 0 or 1: x % 2 . If that result is 0, then we know that the number is even; if the result is 1, then we know the number is odd.

One last operator is the unary minus operator and that is simply a minus sign in front of a variable: -x . This operator simply flips the sign of the variable. There is a unary plus operator for symmetry, but it doesn’t really do anything!

Compound Assignment

We can combine the arithmetic operators with the assignment operator to perform arithmetic and assign it to the same variable. For example, suppose we wanted to step a counter variable i from 0 to 100 in increments of 3. We can use Swift’s shorthand do this succinctly: i += 3 . This is the same as x = x + 3 . We can do this compound assignment for any of the arithmetic operators we discussed.

Comparison Operators

In addition to performing basic arithmetic, Swift gives us operators to compare different numerical variables. Below is a list of all of the comparison operators we can use. You’ll recognize most of these from mathematics:

  1. Equality: x == y
  2. Inequality: x != y
  3. Greater than: x > y
  4. Less than: x < y
  5. Greater than or equal to: x >= y
  6. Less than or equal to: x <= y

It’s important to note that the equals sign in both the greater than or equal to and the less than or equal two must come after the angle bracket. Another very important thing to note is that the assignment operator is different than the equality operator! A common mistake is to use the single equals assignment operator when you meant the double equals equality operator. Luckily, Swift will look for this and warn us. The equality and inequality operators can also be used to check if two strings are equal or not equal: helloPlayground == “Hello, playground!” .

Ternary

Suppose we needed to check if a number was even or odd and return a value depending on the answer to that boolean. We’ll talk about if statements more in depth later, but here’s what we would have to do:

var x = 3
var parity = "Unknown"
if x % 2 == 0 {
    parity = "Even"
} else {
    parity = "Odd"
}

This is fairly boilerplate and simple code, but it’s taking up too many lines! Swift provides us the ternary operator as a way to reduce this if-else statement down to a single line.

var x = 3
var parity = x % 2 == 0 ? "Even" : "Odd"

The ternary operator is called the ternary operator since it takes in three operands: a boolean and two results. If the boolean is true, the result between the question mark and colon is the return value; if the boolean is false, the result after the colon is returned. This allows us to write terse code and not clutter up the codebase with many if-else statements.

Nil Coalescing

If we remember back to when we learned about optionals, we also discussed forced unwrapping and optional binding. Back then, we used if-else statements to check if the optional was nil or not. A common practice is to set an optional’s value to some default in case the value is nil or not. We could do this using if statements or the new ternary operator we just learned about. Let’s look at the following example:

var buildMaterial: String?
var defaultBuildMaterial = "Wood"
var buildingStructure = buildMaterial != nil ? buildMaterial! : defaultBuildMaterial

Note that we use the ternary operator to check if the optional is nil, which it is since we didn’t initialize it with a value. If it is not nil, then we forcibly unwrap the optional’s value. If it is nil, then we set the variable to a default value. This is such common practice that Swift provides an operator to do this for us.

var buildMaterial: String?
var defaultBuildMaterial = "Wood"
var buildingStructure = buildMaterial ?? defaultBuildMaterial

This code snippet and the one above it are the exact same. The nil coalescing operator allows us to shorten the ternary statement to a double question mark. If left optional is nil, then the right operand is used. However, if the left optional is not nil, then it’s value is forcibly unwrapped. The nil coalescing operator is a common shorthand we’ll see in Swift to simply using optionals.

Ranges

In addition to single numbers, Swift also allows us to work with ranges of numbers. Suppose we wanted to print out all of the numbers between 1 and 100. We can use a for-in loop (discussed later in Control Flow) and a range operator like the following.

for value in 1...100 {
    print(value)
}

This operator is called the closed range operator since it represents a mathematically closed interval where the right value is included in the interval. To use this operator, we simply put a set of triple periods between the lowermost and uppermost values and Swift will iterate through every integer between those including the uppermost value.

Complimentary to the closed range operator, Swift also provides a half open operator, which is called half open since the uppermost value is not included in the interval. Suppose we wanted to print the numbers between 1 and 100, but not including 100. We can use the half open operator.

for value in 1..<100 {
    print(value)
}

To use the operator, we simply put 2 periods and a less-than angle bracket between the lowermost and uppermost bounds. The uppermost bound will not be in the interval! This is particularly useful for when we talk about arrays. Using the half open range operator, we can easily iterate through all of the elements in an array.

Logical

Similar to the comparison operators that dealt with booleans, we also have the logical operators that can also deal with booleans in the sense that it can combine them. We have the logical NOT (!), logical AND (&&), and logical OR (||) operators. The first simply negates the value of a boolean: a true becomes a false and a false becomes a true. The logical AND operator returns true only if both operands are true. The logical OR operator returns true if at least one of the operands is true. In code, let’s see an example.

var knowsPassword = false
var enteredThumbprint = false
var knowsBackdoor = true
var hasSecurityOverride = false

if knowsPassword && enteredThumbprint {
    print("ACCESSING SYSTEM...")
} else {
    print("INTRUDER ALERT!")
}

if knowsBackdoor || hasSecurityOverride {
    print("ACCESSING SYSTEM...")
} else {
    print("INTRUDER ALERT!")
}

We can even combine these logical operators to form more complicated conditions.

if (knowsPassword && enteredThumbprint) || knowsBackdoor || hasSecurityOverride {
    print("ACCESSING SYSTEM...")
} else {
    print("INTRUDER ALERT!")
}

The logical operators are evaluated from left-to-right so using parentheses to add precedence and readability is always a good idea! Here’s a table to summarize the logical operators.

Swift for Beginners – 2 – 1

Knowing how to use the logical operators allows us to construct more complicated conditions and will help us better structure our apps.