Notice: Undefined index: understanding-swift in /var/sites/ on line 89
Why would you want to make an infinite loop? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Why would you want to make an infinite loop?

Paul Hudson    @twostraws   

Infinite loops are program loops that continue effectively forever. In Swift, they look like this:

while true {
    print("I'm alive!")

print("I've snuffed it!")

In that code, “I’m alive!” will be printed again and again forever, whereas the “I’ve snuffed it!” message will never be printed – the loop won’t end, so the message won’t be printed. In practice, you’re more likely to have some sort of condition to your loop, like this:

var isAlive = false

while isAlive == true {
    print("I'm alive!")

print("I've snuffed it!")

That allows you to end the loop when you’re ready, so they aren’t truly infinite. As a result, programmers will often call these pseudo-infinite loops – they will run for a long time, and perhaps indeed forever in the case of critical systems that never restart, but technically they aren’t truly infinite.

You might wonder why this sort of code is useful, but actually it’s really common. For example, all the apps you use on your iPhone have infinite loops. Think about it: when your app launches it needs to repeat a series of instructions until it’s told to stop:

  1. Check for any user input
  2. Run any code you need
  3. Redraw the screen
  4. Repeat

That might last for 10 seconds if you’re just checking Twitter, but it might last for hours if you’re playing a game – or perhaps it might run for much longer. The point is that we don’t know when the loop will stop, so we can just loop from 1 to a billion.

Instead, they use something like an infinite loop a bit like the one I showed you earlier – the program will continue to run again and again until it’s time to close, at which point the loop can finish and any clean up code can run.

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

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

Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.