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