enumerate() returns a lazy sequence containing pairs of elements with consecutive Ints, starting from 0. Therefore with arrays, these numbers will correspond to the given index of each element – however this may not be the case with other kinds of collections.
In Swift 3, the stride(_:_:) methods on Stridable have been replaced by the global stride(_:_:_:) functions:
For-in loop with filtering
By adding a where clause you can restrict the iterations to ones that satisfy the given condition.
It's useful when you need to iterate only through the values that match some pattern:
Also you can filter optional values and unwrap them if appropriate by adding ? mark after binding constant:
Similar to the while loop, only the control statement is evaluated after the loop. Therefore, the loop will always execute at least once.
Sequence Type forEach block
A type that conforms to the SequenceType protocol can iterate through it's elements within a closure:
The same could also be done with a named parameter:
*Note: Control flow statements (such as break or continue) may not be used in these blocks. A return can be called, and if called, will immediately return the block for the current iteration (much like a continue would). The next iteration will then execute.
A while loop will execute as long as the condition is true.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0