Swift Loops
Introduction
Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. In Swift, loops are essential for tasks like processing collections of data, performing operations a specific number of times, or continuing an action until a certain condition is met.
Swift provides several types of loops, each designed for different scenarios:
- For-in loops: Iterate over sequences like arrays, ranges, or characters in a string
- While loops: Execute code as long as a condition remains true
- Repeat-while loops: Similar to while loops but guarantee at least one execution
In this tutorial, we'll explore each type of loop in detail with practical examples to help you understand when and how to use them effectively.
For-in Loops
The for-in loop is one of the most commonly used loops in Swift. It allows you to iterate over elements in a sequence, such as arrays, dictionaries, ranges, and strings.
Basic Syntax
for item in collection {
// code to execute for each item
}
Looping Through Ranges
To execute code a specific number of times, you can use ranges:
// Closed range: includes both 1 and 5
for number in 1...5 {
print("Number is \(number)")
}
Output:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
If you don't need the value from the range, you can use an underscore (_
) instead:
// Print "Hello!" 3 times
for _ in 1...3 {
print("Hello!")
}
Output:
Hello!
Hello!
Hello!
Half-Open Range
Swift also provides half-open ranges that exclude the upper bound:
// Half-open range: includes 1 but not 5
for number in 1..<5 {
print("Number is \(number)")
}
Output:
Number is 1
Number is 2
Number is 3
Number is 4
Looping Through Collections
Arrays, strings, and other collections can be iterated using for-in loops:
let fruits = ["Apple", "Banana", "Cherry", "Date"]
for fruit in fruits {
print("I like \(fruit)")
}
Output:
I like Apple
I like Banana
I like Cherry
I like Date
Looping with Enumerated()
If you need both the index and value while iterating, use the enumerated()
method:
let vegetables = ["Carrot", "Broccoli", "Spinach"]
for (index, vegetable) in vegetables.enumerated() {
print("\(index + 1): \(vegetable)")
}
Output:
1: Carrot
2: Broccoli
3: Spinach
Looping Through Dictionaries
When looping through a dictionary, each item is a tuple containing a key and a value:
let heights = ["Tim": 180, "Kim": 165, "Jim": 190]
for (name, height) in heights {
print("\(name) is \(height) cm tall")
}
Output:
Tim is 180 cm tall
Kim is 165 cm tall
Jim is 190 cm tall
Note: Dictionary items are not stored in any particular order, so the output order may vary.
While Loops
A while loop performs a set of statements until a condition becomes false. They're useful when you don't know in advance how many times the loop will need to execute.
Basic Syntax
while condition {
// code to execute while condition is true
}
Simple While Loop Example
var count = 1
while count <= 5 {
print("Count is \(count)")
count += 1
}
Output:
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Reading Input Until a Condition
While loops are useful for processing input until a certain condition is met:
// Simulating user input with an array
let inputs = ["apple", "banana", "quit", "orange"]
var index = 0
while index < inputs.count {
let input = inputs[index]
if input == "quit" {
print("Quitting...")
break
}
print("Processing: \(input)")
index += 1
}
Output:
Processing: apple
Processing: banana
Quitting...
Repeat-While Loops
The repeat-while loop is similar to a while loop, but it executes the code block at least once before checking the condition.
Basic Syntax
repeat {
// code to execute at least once
} while condition
Simple Repeat-While Loop Example
var number = 1
repeat {
print("Number is \(number)")
number += 1
} while number <= 5
Output:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
When the Condition Is Initially False
The key difference between while
and repeat-while
becomes apparent when the condition is initially false:
var count = 10
// This loop won't execute at all
while count < 10 {
print("While loop: \(count)")
count += 1
}
// This loop will execute once
repeat {
print("Repeat-while loop: \(count)")
count += 1
} while count < 10
Output:
Repeat-while loop: 10
Control Transfer Statements
Swift provides statements that change the flow of execution within loops:
Break Statement
The break
statement ends execution of a loop immediately:
for number in 1...10 {
if number == 5 {
print("Breaking at \(number)")
break
}
print("Number: \(number)")
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Breaking at 5
Continue Statement
The continue
statement skips the current iteration and proceeds to the next:
for number in 1...10 {
if number % 2 == 1 { // Skip odd numbers
continue
}
print("Even number: \(number)")
}
Output:
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10
Labeled Statements
When working with nested loops, you can label your statements to specify which loop a break
or continue
should affect:
outerLoop: for i in 1...3 {
innerLoop: for j in 1...3 {
if i == 2 && j == 2 {
print("Breaking outer loop when i=\(i), j=\(j)")
break outerLoop
}
print("i=\(i), j=\(j)")
}
}
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Breaking outer loop when i=2, j=2
Practical Examples
Example 1: Calculating Factorial
func factorial(of number: Int) -> Int {
var result = 1
for i in 1...number {
result *= i
}
return result
}
let num = 5
print("Factorial of \(num) is \(factorial(of: num))")
Output:
Factorial of 5 is 120
Example 2: Finding Prime Numbers
func isPrime(_ number: Int) -> Bool {
guard number > 1 else { return false }
var i = 2
while i * i <= number {
if number % i == 0 {
return false
}
i += 1
}
return true
}
print("Prime numbers between 1 and 20:")
for num in 1...20 {
if isPrime(num) {
print(num, terminator: " ")
}
}
Output:
Prime numbers between 1 and 20:
2 3 5 7 11 13 17 19
Example 3: Processing User Input
This example simulates processing user commands until they decide to quit:
// Simulating a command processor
func processCommands() {
// In a real app, this would come from actual user input
let commands = ["list", "add", "delete", "help", "quit"]
var index = 0
repeat {
// Simulate getting the next command
let command = commands[index]
index += 1
// Process the command
switch command {
case "list":
print("Listing all items...")
case "add":
print("Adding new item...")
case "delete":
print("Deleting item...")
case "help":
print("Showing help menu...")
case "quit":
print("Quitting application...")
return
default:
print("Unknown command")
}
} while index < commands.count
}
processCommands()
Output:
Listing all items...
Adding new item...
Deleting item...
Showing help menu...
Quitting application...
Summary
Swift loops are powerful constructs that allow you to execute code repeatedly in different ways:
- For-in loops are ideal for iterating through ranges, arrays, dictionaries, and other sequences
- While loops execute code while a condition remains true
- Repeat-while loops execute code at least once, then continue while a condition remains true
- Control transfer statements like
break
andcontinue
provide precise control over loop execution
When deciding which loop to use:
- Use
for-in
when you know the number of iterations in advance - Use
while
when you need to check a condition before executing code - Use
repeat-while
when you need to execute code at least once
Exercises
- Write a program that prints the first 10 Fibonacci numbers using a loop
- Create a function that checks if a string is a palindrome (reads the same backward as forward) using loops
- Write a program that uses nested loops to print a simple triangle pattern:
*
**
***
****
***** - Create a function that finds the largest and smallest numbers in an array using a loop
- Write a loop that calculates the sum of all even numbers between 1 and 100
Additional Resources
- Swift Documentation - Control Flow
- Swift Playgrounds - A great way to practice Swift loops interactively
- Ray Wenderlich Tutorials - Contains many practical examples using Swift loops
Remember, the best way to master loops is through practice. Try solving different problems using various loop constructs to build your understanding and intuition.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)