Conditional Statements in Swift

Control flow is a fundamental concept in Swift, as it is in all programming languages, guiding the execution of your code in various directions, like a river being directed by its banks. It enables your programs to perform different actions based on certain conditions, repeat tasks, and navigate through collections of data.

article

Control flow is a fundamental concept in Swift, as it is in all programming languages, guiding the execution of your code in various directions, like a river being directed by its banks. It enables your programs to perform different actions based on certain conditions, repeat tasks, and navigate through collections of data.


Conditional Statements in Swift


Conditional statements allow your program to execute different blocks of code based on certain conditions.


If and If-Else Statements


The if statement is the most straightforward conditional statement. It executes a block of code if, and only if, a condition is true.


            
var temperature = 30
if temperature > 25 {
 print("It's a hot day")
 } else {
 print("It's not so hot")
 }
            
        

For multiple conditions, if-else if chains can be used when we need to check a condition on multiple values.


    
if temperature > 25 {
print("It's a hot day")
} else if temperature < 10 {
print("It's a cold day")
} else {
print("It's a nice day")
}
    

Theoretically, we can make a If-Else statement as long as we want. The main problem is here that it can hit the performance in a negative way. So when we have something more versatile or more advanced, we can actually use a switch statement instead.

Switch Statements in Swift


Swift’s switch statement is more versatile and can compare against multiple types of data, including strings and ranges.


    
let someCharacter: Character = "z"

switch someCharacter {
case "a", "e", "i", "o", "u":
 print("\(someCharacter) is a vowel.")
 case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
 print("\(someCharacter) is a consonant.")
 default:
 print("\(someCharacter) is not a vowel or a consonant")
 }
    

Swift's switch statements must be exhaustive, meaning every possible value must be accounted for, either explicitly or by using a default case. No exhaustive value will end in a compiler error!


Loops in Swift

Loops play a crucial role in programming, allowing us to execute a piece of code multiple times without redundancy. Swift provides several types of loops, each designed to handle repetition based on different scenarios. Understanding these loops and knowing when to use each type can greatly enhance your ability to process collections of data and perform repeated operations efficiently.


For-In Loops


The for-in loop is perhaps the most commonly used loop in Swift. It simplifies iterating over a sequence, such as arrays, ranges, or strings, executing a block of code for each item in the sequence.


    
for number in 1...5 {
print("Number \(number)")
}
    

In this example, number takes on each value from 1 to 5 in turn, and the print statement is executed five times, printing each number.


For-in loops are also incredibly versatile when working with collections:


    
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
    print("I love \(fruit)")
}
    

Here, each fruit in the fruits array is accessed in sequence, demonstrating how easily for-in loops work with arrays.


While Loops


While loops perform a set of statements until a condition becomes false. This loop is ideal when the number of iterations is not known before the loop starts. The condition is checked at the start of each iteration.


        
var timer = 5
while timer > 0 {
print("\(timer)...")
timer -= 1
}
print("Go!")
        
    

The loop repeatedly checks if timer is greater than 0, prints the countdown, and decrements timer. Once timer is no longer greater than 0, the loop exits.


Repeat-While Loops


Swift's repeat-while loop is similar to a while loop but with a key difference: the condition is checked at the end of each iteration, not the beginning. This ensures that the loop's body is executed at least once, regardless of the condition.


    
var attemptsLeft = 3
repeat {
    print("Attempt \(attemptsLeft)")
    attemptsLeft -= 1
} while attemptsLeft > 0
    

Even if attemptsLeft starts as 0, the message will be printed once because the condition is checked after the loop body executes.


Deciding Which Loop to Use


  • Use a for-in loop when you need to iterate over a collection or range of numbers. It's the most straightforward loop for such cases and the one you'll likely use most often.
  • Opt for a while loop when you have an uncertain number of iterations and you need to check a condition before each iteration. It's suitable for loops where the condition may never be true, and thus the loop body should not execute at all.
  • Choose a repeat-while loop when you must ensure the loop's body executes at least once and the condition to continue is checked after each iteration.

Understanding these loops and their specific use cases is essential for effective programming in Swift. They allow you to write clean, efficient code, especially when dealing with repetitive tasks or iterating over data collections. As you become more familiar with each type of loop, you'll find yourself instinctively knowing which to use for any given scenario, making your Swift programming more fluent and intuitive.

instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!