O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 } 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required