We also use for loops to iterate over sequences like strings and arrays. We can run into problems when we manipulate a sequence while iterating on it.
For example, if we append elements to an array while iterating on it:
var fruits = ["banana", "orange"]
for _ in fruits {
fruits.append("kivi")
}
Every time we enter this loop, we add a kivi item to the end of the array that we are iterating through.
Swift arrays are values, so the for loop goes through a copy of fruits made when the loop starts. This loop runs only twice and fruits ends up with 4 items. It is not infinite, but it hides a trap: a loop that checks the array's current size on every pass never ends:
var i = 0
while i < fruits.count {
fruits.append("kivi")
i += 1
}
This loop never makes it to the end of the array. It keeps growing forever!
This is an infinite loop. You can imagine that as programmers, we want to make sure we never write infinite loops as they make our program run forever and completely unusable.
Assignment
Follow the Coding Tutorial and let's practice with infinite for loops!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.