Intro to Operators

Introduction

Welcome to Lesson 11 of The Swift Fundamentals. In Lesson 9, You’ve tasted the power of Swift operators for replacing a traditional else-if statement with a tertiary operator. In this lesson, you will be able be recognize a number of operators and use them when appropriate.

Problem

Write less, produce more

Definition

An operator is a symbol for a function.

Unary operators

1. !true // false
2. !false // true

Binary operators

1. 1 + 2
2. 4 == 4
3. 1 / 4
4. 5 % 2

Typical Else-If

Create an else-if statement.

1. let iCanDrink = false

3. if iCanDrink {
4. print("You may enter")
5. } else {
6. print("No no")
7. }

Needlessly complex.

Tertiary Operator

Instead of writing the long else-if block. You may use an operator to achieve the same effect.

1. iCanDrink ? print("You may enter") : print("No no") // "No no"

The statement above states, if iCanDrink is true, print("You may drinK"), else, print("No no").

Add odd/even numbers

In Lesson 9, we created odd and even arrays.

1. var evenNumbers: [Int] = []
2. var oddNumbers: [Int] = []

4. for number in 1...50 {
5. if number % 2 == 0 {
6. evenNumbers.append(number)
7. } else {
8. oddNumbers.append(number)
9. }
10. }

Tertiary Operator

Since there are only two conditions, a tertiary operator is used instead.

1. for number in 1...50 {
2. (number % 2 == 0) ? evenNumbers.append(number) : oddNumbers.append(number)
3. }

Unwrapping Optionals

You may unwrap optionals without using if-let. You may use a good old way.

1. var age: Int? = nil
2. var defaultAge: Int = 20

4. var finalUserAge = Int() // 0

6. if age != nil {
7. finalUserAge = age!
8. } else {
9. finalUserAge = defaultAge
10. }

Needlessly complex.

Nil-Coalescing Operator

Let us type less but produce more.

1. finalUserAge = age ?? defaultAge // finalUserAge is 20

The above states that if age contains nil, use defaultAge instead. Nice and simple.

Source Code

1011_operators.playground

Conclusion

You’ve only scratched the surface. In Chapter 10, you will learn how to create your own operators. I know you are excited. Stay consistent and you will get there, hopefully soon.

In the next lesson, you will learn how to create fake names for types. Keep marching forward.