Mohamed Omar

100 Days of SwiftUI - Day 5

Pardon the (weeks-long) interruption. I'm back on the Swift train after a few weeks of successful procrastination.

Day 5 of 100 Days of SwiftUI covers the electric world of conditional logic. Just like previous lessons, the similarities to JavaScript thankfully keep on coming.

Conditionals in Swift boil down to boolean values, no matter the data types you're comparing.

For example, the following conditional check will either be true or false.

var smallNumber = 1
var largeNumber = 10

if smallNumber < largeNumber {
  print("\(smallNumber) is less than \(largeNumber)")
}

As would this one:

var earlyLetter = "A"
var lateLetter = "Z"

if earlyLetter < lateLetter {
  print("\(earlyLetter) comes before \(largeNumber)")
}

We can also check multiple conditionals and use else blocks, just like in JavaScript (and many other languages).

var age = 16
var country = "Canada"

if age >= 16 && country == "Canada" {
  print("You can drive here!")
} else {
  print("Sorry, you can't drive!")
}

Switch statements

Switch statements are also available, but they have an interesting twist. A switch statement in Swift has to be exhaustive if it's comparing enums. So a case has to be written for every item in the enum:

enum Cars {
  case toyota, honda, mazda
}

var bestCar = Cars.honda

switch bestCar {
    case .toyota:
        print("Toyota makes great cars")
    case .mazda:
        print("Mazda makes really nice cars")
    case .honda:
        print("Honda makes the best cars")
}

When comparing strings, we can't list every string in existence (there's at least dozens of them!), so instead we provide a default value to fallback to:

let favouriteBand = "Radiohead"

switch favouriteBand {
case "Metallica":
    print("Metallica are still around in 2023!")
case "Weezer":
    print("Oh, that's nice")
case  "The Beatles":
    print("Very original")
default:
    print("You've probably never heard of them")
}

I do like that in Switch you don't need to write a break after ever case. Swift automatically stops running the Switch statement once a case is found to be a match. If we want to override this, we can use the fallthrough keyword.

Ternary

Lastly, Swift also supports ternary operators, which can be very handy for quick checks that don't need an if/else or switch statement.

let food = "pizza"
let isHealthy = food == "pizza" ? "Yes" : "Yes, just trust me"

print("Is \(food) healthy? \(isHealthy)")

That's all for Day 5. I hope to get to Day 6 soon, and not after another weeks-long intermission.