Updated for Xcode 15
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:
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.
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!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.