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.
Write less, produce more
An operator is a symbol for a function.
!true // false
!false // true
1 + 2
4 == 4
1 / 4
5 % 2
Create an else-if
statement.
let iCanDrink = false
if iCanDrink {
print("You may enter")
} else {
print("No no")
}
Needlessly complex.
Instead of writing the long else-if
block. You may use an operator to achieve the same effect.
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")
.
In Lesson 9, we created odd and even arrays.
var evenNumbers: [Int] = []
var oddNumbers: [Int] = []
for number in 1...50 {
if number % 2 == 0 {
evenNumbers.append(number)
} else {
oddNumbers.append(number)
}
}
Since there are only two conditions, a tertiary operator is used instead.
for number in 1...50 {
(number % 2 == 0) ? evenNumbers.append(number) : oddNumbers.append(number)
}
You may unwrap optionals
without using if-let
. You may use a good old way.
var age: Int? = nil
var defaultAge: Int = 20
var finalUserAge = Int() // 0
if age != nil {
finalUserAge = age!
} else {
finalUserAge = defaultAge
}
Needlessly complex.
Let us type less but produce more.
finalUserAge = age ?? defaultAge // finalUserAge is 20
The above states that if age
contains nil
, use defaultAge
instead. Nice and simple.
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.