Skip to main content
  1. SwiftUI in 100 Days Notes/

Day 5 - Swift Conditional Statements: If , Else If, Switch Case, Ternary Operator

In Swift, we may need to check some conditions. We may want to do different operations depending on whether the condition is true or false. For example;

  • If a student’s exam result is above 80, we may want to print a success message on the screen.
  • When we add data to an Array, if there will be more than 3 data, we may want to delete the oldest one.

Of course, we can increase the above situations. But this is the general logic.

In Swift, one of the structures we can check this condition is the if structure.

Swift If Condition #

if someCondition {
    print("Do something")
}

When we examine the code above;

  • The expression starts with if, this tells Swift that we want to check a condition.
  • The someCondition part is where we write the condition.
  • If the condition is true, it writes “Do something” to the terminal, if it is false, it writes nothing.

The code between the { } symbols is called a code block in Swift. In the code example above, the code that will be executed if the condition is true is written between curly brackets.

let score = 85

if score > 80 {
    print("Great job!")
}

In the code above, our condition is score > 80. If the value of the variable score is greater than 80, “Great job!” will be printed on the screen. In our case (since score is 85) the condition is met and the message is printed on the screen.

Comparison Operators #

In the example above, the > operator is called a comparison operator. Because it compares two items and returns true or false.

Let’s examine the comparison operators;

  • > : Greater Than
  • < : Less Than
  • >= : Greater Than or Equal
  • <= : Less Than or Equal.
  • == : Is Equal to
  • != : Is NOT Equal to
let speed = 88
let percentage = 85
let age = 18
let name = "John"

if speed <= 88 {
    print("Where we're going we don't need roads.")
}

if speed > 88 {
    print("Nothing")
//DOES NOT GIVE ANY OUTPUT
}

if percentage < 85 {
    print("Sorry, you failed the test.")
//DOES NOT GIVE ANY OUTPUT
}

if age >= 18 {
    print("You're eligible to vote")
}

if name == "John" {
	print("Greetings John")
}

if name != "" {
	print("There is a name")
}

//OUTPUTS:
//Where we're going we don't need roads.
//You're eligible to vote
//Greetings John
//There is a name

Swift allows us to compare many values with each other. Let’s look at an example;

let firstName = "Paul"
let secondName = "Sophie"

let firstAge = 40
let secondAge = 10

We made our value assignments above, let’s do the comparison below.

print(firstName == secondName) //false
print(firstName != secondName) //true
print(firstName < secondName)  //true
print(firstName >= secondName) //false

print(firstAge == secondAge) //false
print(firstAge != secondAge) //true
print(firstAge < secondAge)  //false
print(firstAge >= secondAge) //true

In the background, Swift is smart and can compare String expressions in letter order. This is not limited to Strings. For example, we can also easily compare Date type data in Swift.

If we want to compare values of enum type, we need to add Comparable to the enum expression.

enum Sizes: Comparable {
    case small
    case medium
    case large
}

let first = Sizes.small
let second = Sizes.large
print(first < second)

The output will be true because small comes before large in the enum list.

How to Check Multiple Conditions? #

For checking multiple conditions, we use the else block. The else block is the block of code that will be executed if the condition is not true.

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

If the first case fails, there is another structure called else if that allows us to make a new check.

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")
}

//OUTPUT: Code to run if a is false but b is true

We can add more else if if we want, but the more we add, the more complex our code gets.

Sometimes we may want to check more than one condition. For example, “If the temperature today is greater than 20 degrees Celsius and less than 30 degrees Celsius, let’s print a message on the screen”

let temp = 25

if temp > 20 {
    if temp < 30 {
        print("It's a nice day.")
    }
}

The code above works just fine, but Swift offers us a better alternative here: && and, with this operator, we can combine two conditions and write them as follows.

if temp > 20 && temp < 30 {
    print("It's a nice day.")
}

The || operator means or. For example, suppose we say “If a user is at least 18 years old or has permission from his/her parents, he/she can buy games”. We can code this as follows.

let userAge = 14
let hasParentalConsent = true

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

The ==true part can be removed. In this case the code;

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

Swift Switch Case #

To check more conditions, we can use as many if and else if as we want. But this will significantly reduce the readability of our code. If we were to write an if conditional statement using the weather we created with the enum, it would look like the following.

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

let forecast = Weather.sun

if forecast == .sun {
    print("It should be a nice day.")
} else if forecast == .rain {
    print("Pack an umbrella.")
} else if forecast == .wind {
    print("Wear something warm")
} else if forecast == .snow {
    print("School is cancelled.")
} else {
    print("Our forecast generator is broken!")
}

We can simplify the above code even more and write it as follows with the switch code.

switch forecast {
case .sun:
    print("It should be a nice day.")
case .rain:
    print("Pack an umbrella.")
case .wind:
    print("Wear something warm")
case .snow:
    print("School is cancelled.")
case .unknown:
    print("Our forecast generator is broken!")
}
  1. We start with switch forecast, this tells Swift which value we want to check.
  2. We continue with the case statement, where we specify the cases in our enum expression.
  3. Since each of the case statements checks the Weather enum, we don’t need to write Weather.sun etc. each time.
  4. We use : to specify the beginning of what to do after the matched case.
  5. We place our closing parenthesis to end the switch statement.

Highlights of the Swift Switch Case #

  1. The states controlled in the Switch must be inclusive, i.e. all possible values must be handled in the Switch. For example, for each of the states sun, rain, wind, snow, unknown in the Weather enum above, a case must be created in the Switch.

    let place = "Metropolis"
    
    switch place {
    case "Gotham":
        print("You're Batman!")
    case "Mega-City One":
        print("You're Judge Dredd!")
    case "Wakanda":
        print("You're Black Panther!")
    default:
        print("Who are you?")
    }
    

    Let’s imagine that we are evaluating a switch for a String expression like the one above. In this case it is not possible to write all possible String expressions as case. That is why we use the default keyword.

    The default case contains the code to be executed if no preceding case matches. (Yes default should be at the end.)

  2. In Swift, the first case that matches the condition we check is executed, subsequent cases are not checked.

    But if for some reason we want other cases to be executed, we can use fallthrough.

    let day = 5
    print("My true love gave to me…")
    
    switch day {
    case 5:
        print("5 golden rings")
    case 4:
        print("4 calling birds")
    case 3:
        print("3 French hens")
    case 2:
        print("2 turtle doves")
    default:
        print("A partridge in a pear tree")
    }
    
    //OUTPUT : My true love gave to me…
    //        5 golden rings
    

    Let’s rewrite it using fallthrough.

    let day = 5
    print("My true love gave to me…")
    
    switch day {
    case 5:
        print("5 golden rings")
        fallthrough
    case 4:
        print("4 calling birds")
        fallthrough
    case 3:
        print("3 French hens")
        fallthrough
    case 2:
        print("2 turtle doves")
        fallthrough
    default:
        print("A partridge in a pear tree")
    }
    
    //OUTPUT : My true love gave to me…
    //        5 golden rings
    //        4 calling birds
    //        3 French hens
    //        2 turtle doves
    //        A partridge in a pear tree
    

    Why Switch? #

    1. Switch controls need to be comprehensive. For each possible value we need to have a case block (all cases in the enum) or set a default case, so it is hard to miss a possibility. This is not necessary for if and else if.
    2. When checking a value for more than one possible result, if we use a switch, the value is read only once, whereas in an if structure the value is called each time. This can cause performance problems.

Ternary Operator (?:) #

This operator takes 3 pieces of input. The Ternary Operator allows us to check a condition and return one of two values: one if true and the other if false.

For example, let’s check whether a person can vote based on their age.

let age = 18
let canVote = age >= 18 ? "Yes" : "No"

Here the value of canVote variable will be “Yes”. The above example is actually an if else block. But written in a shorter form.

You can memorize the structure of the Ternary Operator with WTF.

  • What - What is our condition? : age≥18
  • True - Which value will be returned if the condition is true? : “Yes”
  • False - What value will be returned if the condition is false? : “No”

Example:

enum Theme {
    case light, dark
}

let theme = Theme.dark

let background = theme == .dark ? "black" : "white"
print(background)

//OUTPUT : black
  • What : theme == .dark
  • True : “black”
  • False : “white”

You can also read this article in Turkish.
Bu yazıyı Türkçe olarak da okuyabilirsiniz.

This article contains the notes I took for myself from the articles found at SwiftUI Day 5. Please use the link to follow the original lesson.