FullerPrime FullerPrime - 1 month ago 5
Swift Question

How do for-in loops in swift work?

I've used them, I'm familiar with the code and read a number tutorials but I still don't understand exactly how they work in that I can't run through my head what I'm doing and ultimately what I want to achieve, as opposed to say an if statement which can be read in English quite well.

For-loops
have always been something I've struggled with through lack of understanding, can someone offer some insight please?

Answer

The for-in loop performs a set of statements for each item in a range or collection. Swift also provides two range operators a..<b and a...b, as a shortcut for expressing a range of values.

// prints 1-10
for i in 1...10 {
    print(i)
}


// This way has been removed in Swift 3 so use the above
for var i = 1; i <= 10; i+=1 {
    print(i)
}