UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

When should you use a while loop?

Paul Hudson    @twostraws   

Updated for Xcode 15

Swift gives us for and 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…

  • …the user asks us to stop
  • …a server tell us to stop
  • …we’ve found the answer we’re looking for
  • …we’ve generated enough data

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.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.