We’re kicking it up a notch now as the course starts looking at conditional statements, operators and various types of loop.
We’re eased gently enough into Day 5 with basic if
statements that evaluate simple conditions before moving on to if-else
and switch
for checking multiple conditions.
The next thing we look at is the first genuinely new-to-me programming concept in the course so far, a ternary conditional operator. This neat little piece of syntax lets you check a condition then take one of two actions depending on the result, all in one line of code.
Side note: I also love that the way to remember how to use the ternary statement is the abbreviation WTF (What? True : False) 🤣.
In Day 6 we go over for
and while
loops. There’s some new stuff in here for me too such as break and continue for these types of loop.
Checkpoint 3
Ah yes, FizzBuzz. Checkpoint 3 is that classic and simple programming challenge. For anyone not familiar, the idea is to loop through each number from 1 to 100 and:
- If it’s a multiple of 3, print “Fizz”
- If it’s a multiple of 5, print “Buzz”
- If it’s a multiple of 3 and 5, print “FizzBuzz
- Otherwise just print the number
There are so many ways to solve this with even just the basic knowledge we’ve got so far. The most obvious one for me was a series of if else
statements:
for i in 1...100 {
if i.isMultiple(of: 3) && i.isMultiple(of: 5) {
print("FizzBuzz")
} else if i.isMultiple(of: 3) {
print("Fizz")
} else if i.isMultiple(of: 5) {
print("Buzz")
} else {
print(i)
}
}
Just for fun I decided to try and do this as a ternary conditional as well. This looks hideous but also works perfectly!
for i in 1...100 {
i.isMultiple(of: 3) && i.isMultiple(of: 5) ? print("FizzBuzz") : i.isMultiple(of: 3) ? print("Fizz") : i.isMultiple(of: 5) ? print("Buzz") : print(i)
}