Swift — Loops
For loop
// Closed range
for i in 1...5 {
print(i, terminator: " ")
}
print() // 1 2 3 4 5
// Half-open range
for i in 0..<5 {
print(i, terminator: " ")
}
print() // 0 1 2 3 4
// Stride
for i in stride(from: 0, to: 10, by: 2) {
print(i, terminator: " ")
}
print() // 0 2 4 6 8
Iterating collections
let nums = [1, 2, 3, 4, 5]
for num in nums {
print(num, terminator: " ")
}
print()
// With index
for (index, num) in nums.enumerated() {
print("\(index): \(num)")
}
Iterating strings
let word = "Hello"
for char in word {
print(char, terminator: " ")
}
print() // H e l l o
Iterating dictionaries
let ages = ["Alice": 30, "Bob": 25]
for (name, age) in ages {
print("\(name): \(age)")
}
While loop
var count = 0
while count < 5 {
print(count, terminator: " ")
count += 1
}
print() // 0 1 2 3 4
Repeat-while loop
var count = 0
repeat {
print(count, terminator: " ")
count += 1
} while count < 5
print() // 0 1 2 3 4
Labeled statements
outer: for i in 1...5 {
for j in 1...5 {
if i * j > 10 {
break outer
}
print("(\(i),\(j))", terminator: " ")
}
print()
}
Mini Practice
Write Swift code that:
- Uses
strideto iterate with custom step - Enumerates a collection with index
- Uses
repeat-whilefor a menu loop - Uses labeled break to exit nested loops
Up Next
In the next lesson, you'll learn about Functions — defining and using functions in Swift.
Related Topics
Frequently Asked Questions about Loops
What is Loops in Swift?
Loops is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Loops?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Loops.
Why is Loops important in Swift?
Loops is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.