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.
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 allow your program to execute different blocks of code based on certain conditions.
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.
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 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.
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 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.
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.
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.
Exodai INSTRUCTOR!
Owner and Swift developer!