Swift For-In Loop
Iterate through collections and sequences efficiently
🔄 What is For-In Loop?
Swift for-in loops iterate through sequences like arrays, ranges, and strings. They provide a clean, readable way to process each element in a collection without manual index management.
// Basic for-in loop
let colors = ["red", "green", "blue"]
for color in colors {
print("Color: \(color)")
}
Output:
Color: red
Color: green
Color: blue
For-In Loop Variations
Array Iteration
Loop through array elements
for item in array {
print(item)
}
Range Iteration
Loop through number ranges
for i in 1...5 {
print(i)
}
String Iteration
Loop through string characters
for char in "Hello" {
print(char)
}
Dictionary Iteration
Loop through key-value pairs
for (key, value) in dict {
print("\(key): \(value)")
}
🔹 Iterating Through Arrays
The most common use of for-in loops:
let animals = ["🐶", "🐱", "🐰", "🐸"]
for animal in animals {
print("Animal: \(animal)")
}
// With enumerated() to get index
for (index, animal) in animals.enumerated() {
print("\(index + 1). \(animal)")
}
Output:
Animal: 🐶
Animal: 🐱
Animal: 🐰
Animal: 🐸
1. 🐶
2. 🐱
3. 🐰
4. 🐸
🔹 Range-Based Loops
Use ranges to create numeric sequences:
// Closed range (includes both ends)
for i in 1...5 {
print("Closed range: \(i)")
}
// Half-open range (excludes upper bound)
for i in 1..<5 {
print("Half-open range: \(i)")
}
// Reverse order
for i in (1...5).reversed() {
print("Reverse: \(i)")
}
Output:
Closed range: 1, 2, 3, 4, 5
Half-open range: 1, 2, 3, 4
Reverse: 5, 4, 3, 2, 1
🔹 Dictionary Iteration
Loop through dictionaries to access keys and values:
let scores = ["Alice": 95, "Bob": 87, "Carol": 92]
// Iterate through key-value pairs
for (name, score) in scores {
print("\(name) scored \(score)")
}
// Iterate through keys only
for name in scores.keys {
print("Student: \(name)")
}
// Iterate through values only
for score in scores.values {
print("Score: \(score)")
}
Output:
Alice scored 95
Bob scored 87
Carol scored 92
Student: Alice, Bob, Carol
Score: 95, 87, 92
🔹 String Character Iteration
Process each character in a string:
let word = "Swift"
for character in word {
print("Character: \(character)")
}
// Count vowels example
let text = "Hello World"
var vowelCount = 0
for char in text.lowercased() {
if "aeiou".contains(char) {
vowelCount += 1
}
}
print("Vowels found: \(vowelCount)")
Output:
Character: S, w, i, f, t
Vowels found: 3