In this tutorial you’ll learn about control flow in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as Atom, SublimeText or VSCode.
Control Flow
Swift provides the following control flow statements:
- for-in loop
- while loop
- if
- switch
- guard
For-in loop
For-in loop is used to iterate over arrays, dictionaries, ranges of numbers or characters in a string.
Iterating over an array:
let groceries = ["Fruits", "Yogurt", "Bread", "Vegetables"]
for item in groceries {
print("item is \(item)")
}
Iterating over a dictionary:
let learnAlphabets = ["a": "apples", "b": "bananas", "c": "cherries", "d": "dragon fruit"]
for (alphabet, fruit) in learnAlphabets {
print("\(alphabet) for \(fruit)")
}
Iterating over a range of numbers:
let rangeOneToFour = 1...4
for i in rangeOneToFour {
print("\(i) x 10 = \(i * 10)")
}
Iterating over characters in a string:
let myName = "Zakhia"
for character in myName {
print("Character is \(character)")
}
Let’s say you want multiples of 2, instead of iterating over a range of numbers like we did before, you can use the function stride(from:to:by:), where you provide a starting number, a limit (not inclusive) and an interval.
var interval = 2
var counter = 0
print("multiples of 2:")
for i in stride(from: 2, to: 14, by: interval) {
counter+=1
print("\(counter) x 2 = \(i)")
}
You will notice that the output doesn’t include the limit 14. Let’s say you want multiples of 3 and you also want the iteration to include the limit you put. You can use the function stride(from:through:by:), where you provide a starting number, a limit (inclusive) and an interval.
interval = 3
counter = 0
print("multiples of 3:")
for j in stride(from: 3, through: 18, by: interval) {
counter+=1
print("\(counter) x 3 = \(j)")
}
Notice that the output now includes the limit 18.
While Loop
You provide a condition in a while loop, whereby iterations keep on going until the condition becomes false. There are two kinds of while loop in Swift:
- while
- repeat-while
// while loop
while counter < 10 {
counter+=1
print(counter)
}
// repeat-while loop
repeat {
counter+=1
print(counter)
} while counter < 10
The difference between a while loop and a repeat-while loop is that a while loop checks its condition before executing codes whilst the repeat-while loop checks its condition only after performing the first iteration.
Conditional Statement
Sometimes you might want to execute some codes only if a condition is true. Let’s say if the weather is sunny then you will go to the beach.
var isSunny = true
if isSunny {
print("I will go to the beach")
}
Now let’s say you will do something else if the weather is not sunny.
isSunny = false
if isSunny {
print("I will go to the beach")
} else {
print("I will watch a movie on Netflix")
}
Now let’s say if the weather is sunny then you will go to the beach, if it’s not sunny but rainy, you will watch a movie on Netflix and if it’s not sunny nor rainy, you will go out with your friend.
let isRainy = false
if isSunny {
print("I will go to the beach")
} else if !isSunny && !isRainy {
print("I will go out with my friend")
} else {
print("I will watch a movie on Netflix")
}
Switch
Switch is an alternative way to the if statement for executing codes based on some conditions. A switch statement must be exhaustive, which means that either you provide all the cases possible or only some cases with a default.
let output = 15 * 3
let myGuess = 45
switch myGuess {
case 40:
print("Guess again")
case 45:
print("Correct answer")
default:
print("Wrong answer")
}
You can provide multiple cases to execute the same piece of codes.
let name = "zakhia"
switch name {
case "Zakhia", "zakhia", "ZAKHIA":
print("That's my name!")
default:
print("Not my name")
}
Guard
A guard statement is like an if statement with an else clause.
func show(value: String?) {
guard let v = value else {
return
}
print("Value is \(v)")
}
show(value: "cat")
Reference
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html