Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chrono1081

macrumors G3
Original poster
Jan 26, 2008
8,811
5,581
Isla Nublar
Hi guys,

C-style for loops have been deprecated in Swift, but I can't find a replacement for how to do something like this:

Code:
for i = 0; i < 100; i+=2 {
//Do stuff here
}

The only way I can currently get it working is something like:

Code:
for case let in 0...100 where n % 2 == 0

But I don't feel like using the modulo operator is the correct approach. Can someone more knowledgable than me in Swift explain how we should handle incrementing by something other than 1? I couldn't find anything in Apples docs or on Stack Overflow. Thanks.
 
Use stride

Code:
for i in 0.stride(through: 100, by: 2) {
print(i)
}

for more complicated conditional checks in For loops, you will likely have to move to a while loop.
[doublepost=1459438058][/doublepost]In your example, I guess I should have used to: instead of through: but you get the idea.
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.