Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use while Loops in Swift
Written by Team Kodeco

In Swift, the while loop is used to repeatedly execute a block of code as long as a certain condition is true. The basic syntax for a while loop is:

while condition {
  // code to be executed
}

The condition can be any expression that evaluates to a Boolean value (true or false). The block of code within the curly braces will be executed as long as the condition is true. Once the condition becomes false, the loop will stop executing.

Here is an example of a simple while loop that counts from 1 to 10:

var count = 1

while count <= 10 {
  print(count, terminator: " ")
  count += 1
}
// Output: 1 2 3 4 5 6 7 8 9 10 

It is important to keep in mind that if the condition is always true, the loop will continue to execute indefinitely, resulting in an infinite loop. To avoid this, make sure that the condition will eventually become false within a finite number of iterations.

© 2024 Kodeco Inc.