Swift – Infinite While Loop

To make a while loop run infinitely, the while loop condition has to be always true. So, if we provide a boolean value of true as condition, or a condition like 1 == 1, that always evaluates to true, then while loop runs indefinitely.

Examples

In the following example, we take a while loop and give true as condition.

main.swift

while true {
    print("Hello World")
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...

Now, in the following example, we take a condition that always evaluates to true in while loop, and make the loop run indefinitely.

main.swift

while 1 == 1 {
    print("Hello World")
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to find run a while loop indefinitely with the help of examples.