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
  2. if iCanDrink {
  3. print("You may enter")
  4. } else {
  5. print("No no")
  6. }

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] = []
  3. for number in 1...50 {
  4. if number % 2 == 0 {
  5. evenNumbers.append(number)
  6. } else {
  7. oddNumbers.append(number)
  8. }
  9. }

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
  3. var finalUserAge = Int() // 0
  4. if age != nil {
  5. finalUserAge = age!
  6. } else {
  7. finalUserAge = defaultAge
  8. }

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.