Tutorial by Examples

The for-in loop allows you to iterate over any sequence. Iterating over a range You can iterate over both half-open and closed ranges: for i in 0..<3 { print(i) } for i in 0...2 { print(i) } // Both print: // 0 // 1 // 2 Iterating over an array or set let names = [&quo...
Similar to the while loop, only the control statement is evaluated after the loop. Therefore, the loop will always execute at least once. var i: Int = 0 repeat { print(i) i += 1 } while i < 3 // 0 // 1 // 2
A while loop will execute as long as the condition is true. var count = 1 while count < 10 { print("This is the \(count) run of the loop") count += 1 }
A type that conforms to the SequenceType protocol can iterate through it's elements within a closure: collection.forEach { print($0) } The same could also be done with a named parameter: collection.forEach { item in print(item) } *Note: Control flow statements (such as break or continu...
where clause By adding a where clause you can restrict the iterations to ones that satisfy the given condition. for i in 0..<5 where i % 2 == 0 { print(i) } // 0 // 2 // 4 let names = ["James", "Emily", "Miles"] for name in names where name.c...
A loop will execute as long as its condition remains true, but you can stop it manually using the break keyword. For example: var peopleArray = ["John", "Nicole", "Thomas", "Richard", "Brian", "Novak", "Vick", "Amanda",...

Page 1 of 1