Swift Operators

by Dimitris Tasios
15 views

In this article, we’ll see the operators used in Swift, alongside examples on how to use them.

1. What Are Operators in Swift?

An operator is Swift performs an action on variables, constants, or literal values, with the intent of producing a new value. For example, let’s see the multiplication operator:

let number = 5 * 4

Here, the multiplication operator uses the literal value of 5 and 4 in order to produce, through multiplication, a new value (their product, 20) which is then saved on our constant name number.

Note: From now, we will variables and constants as variables, for brevity. There is no difference on the operators performed on a variable with those performed on a constant.

All operations must have operands of the same type. Otherwise, we’ll get a compilation error.

2. Types of Operators in Swift

There are multiple types of operators in Swift:

  1. Assignment Operators.
  2. Arithmetic Operators.
  3. Comparison Operators.
  4. Logical Operators.
  5. Miscellaneous Operators.

2.1 Assignment Operators

The first type of operators we’ll see are the assignment operators. These operators assign values to variables; either creating them if they didn’t exist or updating them if they did. Note that the constants (declared with the let keyword) cannot be updated.

2.1.1 Assignment Operator, =

The most common assignment operator is the one with “=” symbol. We can assign a value to any variable, as long as they both have the same type.

An assignment between numbers:

var myVar = 4 // the assignment operator "=" creates a new variable with the value "4"
myVar = 5 // the assignment operator updates the variable with the value "5"

Here, we use the = assignment operator in order to both create a new variable with the name myVar, but also, update its value.

An assignment between Strings:

let aString = "Hello world!" // assigning a String value to a constant

However, we cannot perform an assignment between values of different types:

// the following cannot be done, since they don't have the same type (Int assigned to String variable)
var anotherString = "Hello again"
anotherString = 5 // compilation error

The assignment above is impossible since anotherString is a String and 5 is an Int.

2.1.2 Addition Assignment Operator, +=

There are more assignment operators that use the = in order to perform an additional action before assigning the value to the variable. In this subsection, we’ll see the += assignment operator, which performs addition and then assigns the sum to the variable. For example:

let myConstant = 3
var varForAddition = 5
varForAddition += myConstant // 8, this is equal to varForAddition = varForAddition + myConstant

In this example, the += operator is used in order to add the value of myConstant to the variable varForAddition and then assign the sum to varForAddition.

It should be noted that this operator can be used between Strings as well, in order to concatenate them together.

var messageForConcatenation = "Code Learn"
messageForConcatenation += " Hub" // "Code Learn Hub", concatenation between Strings, with the += operator

2.1.3 Subtraction Assignment Operator, -=

The -= assignment operator performs a subtraction and then assigns the result to the variable. For example:

var varForSubtraction = 10
varForSubtraction -= 4 // 6, equal to varForSubtraction = varForSubtraction - 4

In this example, the -= operator is used in order to subtract the number 4 from the variable varForSubtraction and then assign the result to varForSubtraction.

2.1.4 Multiplication Assignment Operator, *=

The *= assignment operator performs multiplication and then assigns the result to the variable. For example:

var varForMultiplication = 7
varForMultiplication *= 8 // 56, equal to varForMultiplication = varForMultiplication * 4

In this example, the *= operator is used in order to multiply the number 8 with the variable varForMultiplication and then assign the result to varForMultiplication.

2.1.5 Division Assignment Operator, /=

The /= assignment operator performs division and then assigns the result to the variable. For example:

var varForDivision = 100
varForDivision /= 25 // 4, equal to varForDivision = varForDivision / 4

In this example, the /= operator is used in order to divide the number 25 from the variable varForDivision and then assign the result to varForDivision.

2.1.6 Remainder Assignment Operator, %=

The %= assignment operator performs division and then assigns the remainder of the result to the variable. Remember that the remainder of a division is the leftover amount of a division. For example:

var varForRemainder = 100
varForRemainder %= 25 // 0, equal to varForDivision = varForDivision % 4 == 0

In this example, the %= operator is used in order to divide the number 25 from the variable varForRemainder and then assign the remainder of the result to varForRemainder. The division of this example is 100 / 25 = 4, like in the example above and the remainder for it is 0, since (25 * 4) + 0 = 100.

2.2 Arithmetic Operators

In this section, we’ll see the operators that use numbers, with the use of mathematical expressions. The examples below will use two operands for each operator. It’s possible to perform operations with more than 2 operands. Swift will compute the result of the first two and, recursively, perform the same operation again. For example, when adding 4 numbers, Swift will break that operation into the operations, as shown below:

Figure 1. Addition with 4 operands.

In essence, Swift only performs arithmetic operations with two operands; larger operations are broken into smaller ones, starting from the leftmost operation. The order of operations is impacted by the use of parenthesis (), as well as the standard order of mathematical operations.

As mentioned, an arithmetic operation is valid between two values of the same type.

2.2.1 Addition Operator, +

The + operator adds two variables or values together.

let addition = 5 + 2 // 7

In the case of Strings, the + operator concatenates two Strings together in order to form a new one.

let clh = "Code " + "Learn Hub"

2.2.2 Subtraction Operator, –

The - operator subtracts two variables or values.

let subtraction = 100 - 99 // 1

2.2.3 Multiplication Operator, *

The * operator multiplies two variables or values.

let multiplication = 30 * 3 // 90

2.2.4 Division Operator, /

The / operator divides two variables or values.

let division = 30 / 2 // 15

Whenever we are dividing variables and values of type Int, any decimal part is discarded. In order to have more accurate divisions, we should be using Double or Float types:

let divisionOfInts = 30 / 4 // 7
let divisionOfDoubles = 30 / 4.0 // 7.5, same as 30.0 / 4 and 30.0 / 4.0

2.2.5 Remainder or Modulo Operator, %

The % operator extracts the remainder of a division. This operator can only be performed on numbers that are neither Float nor Double. For those two types, we use a function, which is not within the scope of this article.

let remainderOrModulo = 30 % 4 // 2

The result of the % can be validated like this: 30 / 4 = 7 and 30 % 4 = 2, so (4 * 7) + 2 = 30.

2.2.6 Unary Minus Operator, –

This operator inverts the sign of a number. That is, it converts a positive number into a negative and vice versa. Using this operator twice will result in the initial number. More specifically, using this operator an odd number of times will result in the number of the opposite sign. On the other hand, using this operator an even number of times will result in the initial number.

let fiftyTwo = 52
let unaryMinus = -fiftyTwo // -52, operator used 1 (odd) time
let doubleUnaryMinus = -(-fiftyTwo) // -(-52) = 52, operator used 2 (even) times

2.2.7 Unary Plus Operator, +

This operator returns the number it is used on, without additional changes. The purpose of this operator is to provide more clarity and symmetry to our code, by noting the positive numbers with a + icon. All these statements are true in mathematics as well; 5 and +5 are the same number, so the + can be omitted.

let forty = 40
let unaryPlus = +40 // 40, identical to the statement above

2.3 Comparison Operators

The operators that will be described in this section compare the values of two operands and return a Bool value (true or false). The Bool value can be used to make decisions about the flow of our code, more specifically in decision-making blocks and loops. As mentioned, a comparison operation is valid between two values of the same type.

2.3.1 Equal To Operator, ==

The == operator checks whether two variables or values have equal values. This operator does not check for equality in object references. This is done by the === operator, which we will see later in this section.

let thirtySix = 36
let isEqualTo36 = thirtySix == 36 // true, 36=36
let isEqualTo33 = (thirtySix == 33) // false, 36≠33. Parentheses are used for clarity

2.3.2 Not Equal To Operator, !=

The != operator checks whether two variables or values don’t have equal values. This operator does not check for inequality in object references. This is done by the !== operator, which we will see later in this section.

let twentyTwo = 22
let isNotEqual22 = (twentyTwo != 22) // false, 22=22
let isNotEqual23 = (twentyTwo != 23) // true, 22≠23

2.3.3 Greater Than Operator, >

The > operator checks whether the value on the left side of the operator is strictly greater than the value on the right side. This operator doesn’t consider the case of equality between the two values.

let sixtyNine = 69
let isGreaterThan70 = (sixtyNine > 70) // false, 69<70
let isGreaterThan68 = (sixtyNine > 68) // true, 69>68
let isGreaterThan69 = (sixtyNine > 69) // false, 69=69 but this operator doesn't check for equality

2.3.4 Greater Than Or Equal Operator, >=

The >= operator checks whether the value on the left side of the operator is greater than or equal to the value on the right side. This operator considers the case of equality between the two values.

let seventySix = 76
let isGreaterThanOrEqualTo77 = (seventySix >= 77) // false, 76<77
let isGreaterThanOrEqualTo75 = (seventySix >= 75) // true, 76>75
let isGreaterThanOrEqualTo76 = (seventySix >= 76) // true, 76=76, this operator checks for equality

2.3.5 Less Than Operator, <

The < operator checks whether the value on the left side of the operator is strictly less than the value on the right side. This operator doesn’t consider the case of equality between the two values.

let fiftyNine = 59
let isLessThan60 = (fiftyNine < 60) // true, 59<60
let isLessThan58 = (fiftyNine < 58) // false, 59>58
let isLessThan59 = (fiftyNine < 59) // false, 59=59 but this operator doesn't check for equality

2.3.6 Less Than Or Equal To Operator, <=

The <= operator checks whether the value on the left side of the operator is less than or equal to the value on the right side. This operator considers the case of equality between the two values.

let eightyOne = 81
let isLessThanOrEqualTo82 = (eightyOne <= 82) // true, 81<82
let isLessThanOrEqualTo80 = (eightyOne <= 80) // false, 81>80
let isLessThanOrEqualTo81 = (eightyOne <= 81) // true, 81=81, this operator checks for equality

2.3.7 Identity Equality Operator, ===

The === checks whether two classes have the same object reference in memory. Note that we can use this operator only with classes and not structs. That is because classes are “by reference” (each copy of the class points to the same object). On the contrary, structs are “by value” (each copy of the struct is a new copy with a unique reference to it).

For this example, we created a class named SimpleClass. This class has an Int property called classNumber, alongside an initializer to initialize that property during the creation of an instance of our class.

class SimpleClass {
    var classNumber = 0
    
    init(number: Int) {
        self.classNumber = number
    }
}

let classA = SimpleClass(number: 5)
let classB = SimpleClass(number: 5)
let classC = classA

let aPointsToSameAsB = (classA === classB) // false, their values inside are the same but not the objects themselves
let aPointsToSameAsC = (classA === classC) // true, classC points to classA

As you can see, classA and classB are two unique objects that happen to have the same value for their classNumber property. If we were to compare that property of the classes with the == operator, we would get a true value. However, the === checks for object references. Since classA and classB are two unique objects, their references are different, so the equality in line 13 will be false.

On the other hand, classC is created as a copy of classA , and thanks to classes being “by reference”, their references will be the same. So, the equality in line 14 will be true.

2.3.8 Identity Inequality Operator, !==

The !== checks whether two classes have different object references in memory. Just like ===, this operator can only be used with classes. The examples below use the SimpleClass class we mentioned in the subsection above.

let simpleClassA = SimpleClass(number: 4)
let simpleClassB = SimpleClass(number: 5)
let simpleClassC = simpleClassA

let aPointsToDifferentThanB = (simpleClassA !== simpleClassB) // true, different references
let aPointsToDifferentThanC = (simpleClassA !== simpleClassC) // false, same references

2.4 Logical Operators

The logical operators are used between two Bool variables or values, resulting in a new Bool value. These operators are based on operators used in Boolean algebra.

2.4.1 Logical AND Operator, &&

The && operator returns true if both values on either side of it are true. Otherwise, it returns false.

let andTrueOperand = true
let andFalseOperand = false

let trueOperandAndTrue = (andTrueOperand && true) // true, true AND true -> true
let trueOperandAndFalse = (andTrueOperand && false) // false, true AND false -> false

let falseOperandAndTrue = (andFalseOperand && true) // false, false AND true -> false
let falseOperandAndFalse = (andFalseOperand && false) // false, false AND false -> false

2.4.2 Logical OR Operator, ||

The || operator returns true if either value on either side of it are true. Otherwise, it returns false.

let orTrueOperand = true
let orFalseOperand = false

let trueOperandOrTrue = (orTrueOperand || true) // true, true OR true -> true
let trueOperandOrFalse = (orTrueOperand || false) // true, true OR false -> true

let falseOperandOrTrue = (orFalseOperand || true) // true, false OR true -> true
let falseOperandOrFalse = (orFalseOperand || false) // false, false OR false -> false

2.4.3 Logical NOT Operator, !

The ! operator returns true if the operand is false and vice versa.

let notTrueOperand = true
let notFalseOperand = false

let notTrue = !notTrueOperand // false, NOT true -> false
let notFalse = !notFalseOperand // true, NOT false -> true

2.5 Miscellaneous Operators

The operators in this section do not fall into one specific category of the aforementioned ones.

2.5.1 Ternary Operator, ? :

The ternary operator checks a condition and picks one value, depending on whether that condition is true or false. You may read more about the ternary operator in our article here.

2.5.2 Nil-Coalescing Operator, ??

The nil-coalescing operator unwraps an optional value and assigns its unwrapped value to a variable. If the optional is nil, then this operator assigns a default value to the variable. You can read more about the nil-coalescing operator in our article here.

2.5.3 Range Operators

A Range defines a series of consecutive numbers. You may read more about ranges in our article here.

3. Conclusion

By now, you should be able to use Swift’s operators without hesitation. You can find the source code (Playground) on our GitHub page.

4. Sources

[1]: truncatingRemainder Function, Apple

[2]: Basic Operations – Boolean Algebra, Wikipedia

Related Posts