Explain "for in" loop??

Hi, I'm a newbie learning Swift 3 using Apple's iBook The Swift Programming Language (Swift 3 Beta). I came upon "for in" loops and I can't quite grasp it. I know how a "for" loop works but the "for in" loops are really confusing me.

Could someone explain in detail what a "for in" loop does? Like step by step? Any help would be appreciated! Thanks!

Accepted Answer

Essentially, for ... in means :

for x in aRange { }

for all objects in aRange, do something, the curent object is x.


aRange may be just a range of numbers

for i in 10 ..<100 { } // 100 is excluded ; every integer is used (increment is 1)

or

for i in 10...100 { } // 100 is included


it may be much more, like an array

for elem in myArray { } // you explore all the items of the array


syntax may also use a where clause

for i in 10..<100 where i%2 == 0 { } // only even numbers will be used ; equivalent to a loop with increment of 2


You can also ask for reverse order and much more ; read the doc in detail, its very powerful

Thank you so much for answering!

Read what doc?

The doc is the Swift programming language (available on Swift.org).


Please mark the question as solved to make it easier to browse the forum.

Explain "for in" loop??
 
 
Q