- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 136字
- 2021-07-02 23:54:25
for loops
Swift provides for and for-in loops. We can use the for-in loop to iterate over items in a collection, a sequence of numbers such as ranges, or characters in a string expression. The following example presents a for-in loop to iterate through all items in an Int array:
let scores = [65, 75, 92, 87, 68]
var teamScore = 0
for score in scores {
if score > 70 {
teamScore = teamScore + 3
} else {
teamScore = teamScore + 1
}
}
and over dictionaries:
for (cheese, wine) in cheeseWinePairs{
print("\(cheese): \(wine)")
}
As C styles for loops with incrementers/decrementers are removed from Swift 3.0, it is recommended to use for-in loops with ranges instead, as follows:
var count = 0
for i in 0...3 {
count + = i
}