if & Logical Operator & Switch & fallthrough & Ternary conditional operator


if

Check conditions

we want to print a success messages, If the student’s exam score was over or equal 80. ‘score >= 80’ is our Condition which Swift check. if the condition is ture, we print the message.

let score = 85

if score >= 80 {
    print("Top job!")
    print("looking forward to your next score")
}

As we’ve seen how <,>= and others work great with numbers,they work equally well with strings. when we want to sort names alphabetically, we can use them. Arnold starting with ‘A’ is terated Less than Joseph starting with ‘J’. A<B<C<D<E<F<G …

let myName = "Joseph Park"
let friendName = "Arnold Rimmer"

if myName < friendName {
    print("It's \(myName) vs \(friendName)")
}
if myName > friendName {
    print("It's \(friendName) vs \(myName)")
}

If adding a number to an array makes it contain more than 3 items, Remove the oldest one. we can use ‘append()’, ‘count’, and ‘remove(at:)’

var numbers = [1, 2, 3]
numbers.append(4)
if numbers.count > 3 {
    numbers.remove(at: 0)
}
print(numbers)

’==’ means ‘is equal to’

let country = "Canada"
if country == "Australia" {
    print("G'day!")
}

’!=’ means ‘is not equal to’

let name = "Joseph Park"

if name != "Anonymous" {
    print("Welcome, \(name)")
}

Now, we want to chenck whether the username entered by the user is empty.

var username = ""

//1st way to check
if username == "" {
    username = "Anonymous"
}
print("Wlcome, \(username)!")

//2nd way to check, which could be slow
if username.count == 0 {
    username = "Anonymous"
}
print("Wlcome, \(username)!")

//3rd way to check
if username.isEmpty {
    username = "Anonymous"
}
print("Wlcome, \(username)!")

Check Multiple conditions

we want to check for several different values, Swfit provides us with an advanced condition that lets us add an ‘else’ block to our code, some code to run if the condition is not true.

let age = 16
if age >= 18 {
    print("You can drive!")
} else {
    print("Sorry, you are too young to drive.")
}

So, now our condition looks like this

if someCondition {
    print("This will run if the condition is true")
} else {
    print("this will run if the condition is false")
        }

there’s an even more advanced condition called ‘else if’, which lets us run a new check if thefirst one fails. we can have multiple “else if’ and even combine ‘else if’ with an ‘else’ if needed. However, we can only ever have one ‘else’, because that means “if all the other conditions have been false.”

let a = false
let b = true

if a {
    print("Code to run if a is true")
}else if b {
    print("Code to run if a is false but b is true")
} else {
    print("Code to run if both a and b are false")
}

Check more than one thing.

we might want to say “if today’s temperature is over 20 degrees Celsius but under 30, print a message.” This has two conditions. So, we can use ‘&&’ to combine two conditions together, which means ‘and’. the whole condition will only be true if the two parts inside the condition are true.

var temp = 24
if temp > 20 && temp < 30 {
    print("It's a nice day!")
}


Logical Operator

&& will only make a condition be true if both subconditions ar true ||, which means ‘or’ and is called ‘two pipe symbols’, will make a condition be true if either subcondition is true.


we could say that a user can buy a game if he is at least 18 years-old, or if he is under 18, he must have permission from a parent.

let userAge = 14
let hasParentalConsent = true

if userAge >= 18 || hasParentalConsent == true {
    print("You can buy the game")
}

Using ‘== true’ in a condition can be removed, because we’re obviously already checking a Boolean.


Complex example

we’re going to create an enum called TransportOption.

enum TransportOption {
    case airplane, helicopter, bicycle, car, scooter
}

let transport = TransportOption.bicycle

if transport == .airplane || transport == .helicopter {
    print("Let's fly!")
}else if transport == .bicycle {
    print("Let's look up a bike path.")
}else if transport == .car {
    print("Time to get stuck in traffic.")
}else {
    print("I'm gonna ride a scooter!")
}


Switch

we can ‘if’ and ‘else if’ repeatedly to check conditions as many times as we want, but it gets a bit hard to read it. So, we can replace them to ‘switch’

enum Weather {
    case sun, rain, wind, snow, unkonwn
}

let forecast = Weather.wind

switch forecast {
case .sun:
    print("It's a nice day!")
case .rain:
    print("Pack an umbrella.")
case .wind:
    print("Wear something Warm.")
case .snow:
    print("School is cancelled.")
case .unkonwn:
    print("Our forecast generator is broken")
}

switch statements must be exhaustive. we need to provide a ‘default’ case which is a code to run if none of the other cases match. in this case, we don’t have to have enum.

let place = "Metroplis"

switch place {
case "Gothan":
    print("You are Batman.")
case "Wakanda":
    print("You are Black Panther.")
default:
    print("Who are you?")
}


Fallthrough

if we ecplicitly want Swift to carry on executing subsequent cases, use ‘fallthrough’. it can help us avoid repeating work.

let day = 1
print("Days")

switch day {
case 1:
    print("It's Monday")
    fallthrough
case 2:
    print("It's Tuesday.")
    fallthrough
case 3:
    print("It's Wednesday.")
    fallthrough
case 4:
    print("It's Thursday.")
    fallthrough
default:
    print("It's Friday.")
}


Ternary conditional operator

Ternary operators work with Three pieces of input. the ternary operator lets us check a condition and return one of two values: something if the condition is true, and something if it’s false.

let age1 = 18
let canVote = age1 >= 18 ? "Yes, you can vote" : "No, you can't vote"
print(canVote)

Mnemonic is WTF. it stands for “What ? True : False

var hour = 14
print(hour < 12 ? "It's a before noon" : "It's after noon")

with an array.

let names = ["Joe", "Mark", "Paul"]
let howManyPeople = names.isEmpty ? "No one" : "\(names.count) people"
print(howManyPeople)

print(names.isEmpty ? "no" : "\(names.count) people")

with enum

enum Theme {
    case light, dark
}

let theme = Theme.dark

let background = theme == .dark ? "Dark mode" : "Light mode"
print(background)

with Bool

let strongMagnets = true
print(strongMagnets ? "Success" : "Failure")