Swift Conditions: If, Switch and Ternary operator

Swift Conditions: If, Switch and Ternary operator

Β·

8 min read

Hi All, As I told in the previous articles that I have started a #100DaysOfSwiftUI challenge this is my learning from Day 5. where I have learned about Conditions in Swift and its use cases. Let's go through it at once:

Conditions

As in life, we will be always coming across crossroads where we have to make some decisions before moving on. Similarly swift we will be having a code where depending on some condition we will be performing different actions on the code. Like where we decide whether is game is over or not based on the user score or we decide the user is eligible to vote or not based on the age or based on the temperature we decide what is the current weather will be like.

To handle different conditions in Swift we have if-else, switch, and more. let's go through them one by one.

Checking True or False Using If Statement

Swift have IF statements, which let us check a condition and run some code if the condition is true. Which looks like this

if condition {
    print("Do something")
}

let's go through each item in the code snippet

  • First is if, which tells the swift that there is some condition in our code.
  • then some conditions where we give the condition part of code. Like if the score is above 80 users have passed the test. Or if the user's age is over 18 then he can vote.
  • then code between two curly brackets { } which contains the code which is executed if the condition is true.

some example code:

var age: Int  = 19
if age >= 18 {
    print("You are eligible to vote")
}

var gameOver: Bool = false 

if gameOver {
   print("You Played well. Better luck next time")
}

as you see in the above code that we can provide some conditions if the condition is true then our code inside curly braces is executed and in our code first if condition will be executed but the second is false so the print statement will not be executed.

We can create conditions in many forms using angle brackets to check less than, greater than conditions, or using the ! operator to check flipping boolean condition is true or not. also, we can compare the same data types like comparing 2 strings are equal or counting the numbers of char in those strings, etc scenarios.

Checking Multiple Conditions Using If Else

As we learned in the previous section about IF condition where we check a single condition based on it running some code. Similarly, there will be cases where multiple conditions have to be true for some code to run so help us with that situation swift offers us If, Else If, and Else conditions. which looks like this

if someCondition {
   print("Do something")
else if someOtherCondtion {
   print(" Do this")
else {
 print("Atleast do this")
}

As you can see in the above code we check for some conditions if that is not true then we check for the next condition using the else if check and finally none of the conditions is true already we run the code in the else condition. which looks like this:

if speed > 100 {
   print(" You are going too speed. Slow down)
} else if speed > 40{
      print("Maintain the same speed and drive safe")
} else {
      print("Speed up a little. You are going too slow")
}

as you see first we check if the speed is over 100 if that is the case then we print the message if that condition is not true we check if his speed is above then we tell him to keep the same speed and finally since no other conditions are matched we print driver to speed up a little.

Similar to this there is one more type of multiple condition check at the same time which looks like this:

if isOwner==true || is == true {
   print("You can delete this post")
}

if isOwner == true && isEditingEnabled {
  print("You can edit this post")
}

if(isOwner == true && isEditingEnabled) || isAdmin == true {
  print("You can delete this post")
}

In the above code snippet, we can see that we trying to check 2 conditions at the same time and if one of them is true then we run the code inside curly brackets. Also, you can see that I have placed 2 pipes ( || ) between both conditions that are called OR condition operator that mean even when one of the condition is true we can run the code inside the blocks.

In the second example, we are using the 2 && symbols which indicates the AND operator which in our codes that when both the condition is true only we can run the code inside the block.

in the Last example, we use 3 conditions at the same time but && and || operators can only operator 2 conditions at a time using the brackets we are telling swift to which conditions to check first then based on the result of that code to remaining condition and based on the final result we decide whether to execute that code block or not

Switch Statements To Check Multiple Conditions

Switch statements are used in Switch when we have to check multiple and all possible conditions. Let's go through a few conditions where we can make use of the switch statements rather than using if-else statements:

  • Swift requires that its switch statement be exhaustive, which means we have to add a case block for every possible value or you must have a default case. But if we use if-else then we might even accidentally miss a case condition.
  • We use the switch to check a value for multiple possible results that value will only be read once whereas if you use If it will be read multiple times.
  • Swift's switch cases allow for advanced pattern matching that is unwieldy with if.

Now let's see how to use the switch with its counter as an if-else statement.

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

let forecast = Weather.sun

// Using If Else condition
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 == .rain {
    print("School is cancelled.")
} else {
    print("Our forecast generator is broken!")
}

So as you can see in the case of the if-else statement

  • we have to check the condition at every if check.
  • we by mistake checked for .rain conditions twice.
  • we didn't even check for .snow condition at all.

We can solve all these problems using the switch statement.

// Using switch statement
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!")
}

let's breakdown the switch use case;

  • we start with switch forecast, which tells swift that's the value we want to check
  • then we have a string of case statements, each of which is the value we want to compare against the forecast.
  • after each case, we write a colon to mark the start of code to run if that case is matched.
  • we use a closing bracket to show the end of the switch statement.

Swift switch differs from the rest of the programming languages in 2 places:

  • In Swift, the switch statements must be exhaustive means all possible scenarios must be covered otherwise Xcode will throw an error.
  • Swift will execute the first case that matches the condition you are checking but no more. There is one more thing in a switch that is the Default case which Is similar to else in the case of if-else statements.
let day = 3
print("My true love gave to me…")

switch day {
case 3:
    print("3 French hens")
case 2:
    print("2 turtle doves")
default:
    print("A partridge in a pear tree")
}

The default case will handle all other cases which we are not checking already. we will go through it as we learn more about swift in the future.

Ternary Operator

Ternary works with three pieces of input, i.e condition then action to be performed when the condition is true and action to perform when the condition is false.

for example :

let age  =19

let canVote = age >= 18 ? 'Yes" ; "No"

As I told 3 parts first is a condition where we check if age is greater than equals to 18 then question mark indicates the start of statements the needs to execute which are separated by colon first part is the true condition execute code and second part is false condition execution code. A few more examples of ternary operators:

enum Theme {
    case light, dark
}

let theme = Theme.dark

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


let hour = 23
print(hour < 12 ? "It's before noon" : "It's after noon")

//if we used the If-else statement
print(
    if hour < 12 {
        "It's before noon"
    } else {
        "It's after noon"
    }
)

// or this using print inside if-else block
if hour < 12 {
    print("It's before noon")
} else {
    print("It's after noon")
}

So the ternary operators let us choose from one of two results based on a condition, and does in a concise way.

let isAuthenticated = true
print(isAuthenticated ? "Welcome!" : "Who are you?")

some people rely heavily on the ternary operator because it makes a short amount of code. and some stay away since it can make code harder to read. Now there is a lot's use of ternary operators in SwiftUI.

Conclusion

So I have learned on the Day 5 of 100 Days of SwiftUI that how to use Conditions in Swift such as If, else if, switch and finally ternary operators and use cases for them.

Also, let me know if any mistakes are done in this blog/write-up I have done on Day 5 learning so I can fix my mistakes and improve my understandings.

Thank you.