Adam Rush

@Adam9Rush

22 November, 2021

A while loop in Swift performs a set of statements before a condition is false. These loops are best used when you’re not sure about the number of iterations to perform. It’s like queuing for ice cream without the van giving any indication of how long it will take to serve you.

In Swift, there are 2 kinds of while loops.

  • while evaluates it’s condition at the start of each pass through.
  • repeat-while evaluates it’s condition at the end of each pass through.

While

Let’s start with the while loop. The easiest way to understand a while loop is by looking at some examples.

var sports = ["🏉", "⚽️", "🏀", "🎾", "⛳️"]

while !sports.isEmpty {
    sports.removeFirst()
}

print(sports)

Whilst this is a very basic example, you have an array of sports icons. The while statement is !sports.isEmpty which means, whilst the array is not empty continue with the statement which is sports.removeFirst() this will remove the first item in the array and continue with the while condition.

Finally, your console will print an empty array.

[]

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.