The first question I get from coders starting Swift is what's up with the for loops?
What's up with Swift's for loops?
Loops are one of Swifts best features. I know that sounds stupid but use Swift for a few hours and then switch to a language with C style loops. You will know what I'm talking about!
Cool! How do they work?
for i in 0..<100 {
print (i)
}
Let's go through this. In this loop i is the "iterator" it holds the current integer value. 0 then 1 then 2 then 3, all the way up to 99.
0..<100 is a list of integers from 0 to 99. 99 being less than 100
One important thing to remember is that you can't mess with i. Don't try i += 1 to skip an element, it won't work.
For more information on let and var click here
But I want to skip things!
We'll get to that
Where's the foreach?
If you are coming from other languages you might wonder where the foreach is in Swift. Well, it's hiding in plain sight.
var array = Array(0..<100)
for item in array {
print (item)
}
Look familiar? There is only one kind of for loop in Swift. And you use it the same way no matter what you are looping through.
This same loop would work if it was a Dictionary, an Array, or a Set.
But I still want to skip items in my normal loops
It's a little more complicated than in other languages. So, you basically have two choices. Let's say you want to print only the even numbers.
for i in 0..<50 {
print(i*2)
}
or
for i in 0..<100 where i % 2 == 0 {
print(i)
}
WHERE?!?!? I just wanted to loop!
Listen, where is awesome! A lot of coders freak out when they see it. But if you think of it my way you'll be fine.
Remember:
This...
for i in 0..<100 where i % 2 == 0 {
print(i)
}
is exactly the same as...
for i in 0..<100 {
if i % 2 == 0 {
print(i)
}
}
Not so hard, right?