Chapter 5: Control Flow in Swift: Making Decisions and Repeating Tasks
This post is part of a series about programming with Swift to build iOS apps. Be sure to check out the other posts in the series for a complete journey into mastering iOS development.
Now that you’re familiar with variables, constants, and data types in Swift, it’s time to take things a step further. In this post, we’ll explore control flow—how to make decisions in your code and repeat tasks efficiently. This is where your code starts to gain logic and flexibility, making it capable of adapting to different situations.
By the end of this post, you’ll know how to use conditionals and loops to write more dynamic and powerful programs.
What is Control Flow?
Control flow refers to the direction your code takes during execution. It allows your program to:
Make Decisions: Use conditionals to choose between different actions based on specific conditions.
Repeat Tasks: Use loops to perform an action multiple times.
1. Conditionals: Making Decisions
Conditionals let you execute specific parts of your code depending on whether a condition is true or false. The most common conditional statements in Swift are:
if Statements
let temperature = 30
if temperature > 25 {
print("It's a warm day!")
}If the condition
temperature > 25is true, the code inside the braces{}runs.If it’s false, the code is skipped.
if-else Statements
let temperature = 15
if temperature > 25 {
print("It's a warm day!")
} else {
print("It's a cool day.")
}The
elseblock runs if the condition is false.
else if for Multiple Conditions
let temperature = 10
if temperature > 25 {
print("It's a warm day!")
} else if temperature > 15 {
print("It's a mild day.")
} else {
print("It's a cold day.")
}Use
else ifto check multiple conditions in sequence.
Ternary Operator
A shorthand for if-else:
let temperature = 20
let weather = temperature > 25 ? "Warm" : "Cool"
print(weather) // Output: Cool2. Loops: Repeating Tasks
Loops allow you to execute a block of code multiple times. Swift provides several types of loops:
for-in Loop
Use this to iterate over a range or a collection.
for number in 1...5 {
print("Counting: \(number)")
}The loop runs from 1 to 5, inclusive.
Iterating Over an Array
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print(fruit)
}Prints each fruit in the array.
while Loop
Use this when you want to repeat a task while a condition is true.
var counter = 0
while counter < 5 {
print("Counter is \(counter)")
counter += 1
}repeat-while Loop
Similar to while, but it executes the block at least once.
var counter = 0
repeat {
print("Counter is \(counter)") counter += 1
} while counter < 53. Controlling Loops
Sometimes, you may want to skip or stop a loop early. Swift provides:
continue: Skips the current iteration and moves to the next one.
for number in 1...5 {
if number == 3 {
continue
}
print(number) // Skips 3
}break: Exits the loop entirely.
for number in 1...5 {
if number == 3 {
break
}
print(number) // Stops at 2
}Control Flow in SwiftUI
Let’s see how control flow can be used in your SwiftUI app.
Step 1: Create Chapter5View.swift
Add a new Swift file named Chapter5View.swift to your project and add the following code:
import SwiftUI
struct Chapter5View: View {
@State private var temperature = 20
var body: some View {
VStack(spacing: 20) {
Text("Temperature: \(temperature)°C")
.font(.headline)
Text(temperature > 25 ? "It's a warm day!" : "It's a cool day.")
.font(.subheadline)
.foregroundColor(temperature > 25 ? .red : .blue)
Button("Increase Temperature") {
temperature += 5
}
.padding()
}
.padding()
}
}Step 2: Update ContentView.swift
Modify ContentView to load Chapter5View:
import SwiftUI
struct ContentView: View {
var body: some View {
Chapter5View()
}
}
#Preview {
ContentView()
}What’s Happening Here?
@StateProperty: Thetemperaturevariable is marked with@State, allowing SwiftUI to track its changes and update the UI accordingly.Ternary Operator: The text changes dynamically based on the
temperaturevalue.Button: Each tap increases the temperature, demonstrating how control flow integrates with user interaction.
Challenge: Try It Yourself
Create a list of tasks and display only completed tasks in the app using an
ifstatement. Example:
let tasks = ["Buy groceries", "Clean room", "Finish project"]
let completedTasks = ["Buy groceries"]
for task in tasks {
if completedTasks.contains(task) {
print("Completed: \(task)")
}
}Use a loop to create dynamic views in SwiftUI. For example:
VStack {
ForEach(1...5, id: \.self) { number in
Text("Item \(number)")
}
}
What’s Next?
You’ve just unlocked one of the most important concepts in programming: control flow. It’s the foundation for writing logic into your apps, allowing them to adapt to different situations and perform repetitive tasks efficiently.
In the next post, we’ll dive into functions and closures—tools that let you group and reuse your code, making your programs cleaner and more efficient. Let’s keep building!

