Updated for Xcode 14.1
Swift gives us
while loops, and both are commonly used. However, when you’re just learning it can seem odd to have two commonly used ways to make loops – which should you use and why?
The main difference is that
for loops are generally used with finite sequences: we loop through the numbers 1 through 10, or through the items in an array, for example. On the other hand,
while loops can loop until any arbitrary condition becomes false, which allows them until we tell them to stop.
This means we can repeat the same code until…
And those are just a handful of examples. Think about it: if I asked you to roll 10 dice and print their results, you could do that with a simple
for loop by counting from 1 through 10. But if I asked you to roll 10 dice and print the results, while also automatically rolling another dice if the previous dice had the same result, then you don’t know ahead of time how many dice you’ll need to roll. Maybe you’ll get lucky and need only 10 rolls, but maybe you’ll get a few duplicate rolls and need 15 rolls. Or perhaps you’ll get lots of duplicate rolls and need 30 – who knows?
That’s where a
while loop comes in handy: we can keep the loop going around until we’re ready to exit.
SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.
Link copied to your pasteboard.