Using Loops

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the last demo, you improved your calculator to decide which operation to perform based on the value of an input. You learned the difference between if-else and switch statements. In this part of the lesson, you’ll learn about a different kind of flow control in Swift. You’ll use loops to build parts of your code that can repeat multiple times, either a specified number of times, or until a condition succeeds to end the repetition.

Loops have a similarity to if statements. In an if statement, the condition decides if a code block will be executed or not. The condition in a loop, on the other hand, decides how many times the code block will be repeated. It could be once, twice, a thousand times or none at all.

Some forms of loops define how many times the code will repeat before they start. It’s as if you say: “Do this five times”. Other forms of loops repeat until something signals them to stop. Like: “Keep guessing numbers until you find the right one”. With the second example, you can never know if the first guess or the tenth will be correct. You just keep going.

for-in Loops

In Swift, you represent the first kind of loops with the keyword for:

let intArray = [1, 2, 3, 4, 5]
for index in intArray {
  print("\(index)")
}

while Loops

The other kind of loops, the ones that repeat an unknown number of times, come in two versions: while and repeat while. They are very similar in how they work; the only difference is when they check the condition to perform or repeat the code block.

var number = 5 //1
while number < 10 { //2
  print("\(number)")  //3
  number = number + 1
}
var number = 5 //1
repeat  {
  print("\(number)") //2
  number = number + 1
} while number < 10 //3

Loop Breaks and Continues

There are two keywords you can use inside the code block of a loop that can interrupt the flow no matter the value of the loop’s condition. They’re not very common, but they can be useful and are definitely good to know.

var wordsArray = ["Hello", "silence", "my", "old", "friend", "I've" ,"come" ,"to" , "talk", "with", "you", "again", "ABORT", "Because", "a", "vision", "softly", "creeping"] //1
var index = 0 //2
while index < wordsArray.count && wordsArray[index] != "ABORT" { //3
  if wordsArray[index].count > 4 { //4
    print(wordsArray[index])
  }

  index = index + 1 //5
}
for word in wordsArray { //1
  if word == "ABORT" { //2
    break
  }

  if word.count <= 4 { //3
    continue
  }

  print(word) //4
}
See forum comments
Download course materials from Github
Previous: if & switch Demo Next: Loops Demo