A loop is used to execute a sequence of statements multiple times until the stated condition becomes false. A loop usually consists of two parts:
Swift has multiple kinds of loops such as:for-in
, for-each
, and while
loops for repeated execution of a set of statements.
A for loop is used to iterate over dictionaries, arrays, and collections. It goes over each item in these data structures and executes a set of instructions if an item still remains.
The code below shows how the two kinds of for-in
loop and for-each
loop
import Swift// For-in looplet ages = ["John": 28, "Sarah": 12, "Jack": 72]for (name, age) in ages {print("\(name) is \(age) years old")}let names = ["Jack", "Sarah", "John"]for name in names {print(name)}// For-each loopprint("\n Using the for each loop \n")let newAges = ["John": 28, "Sarah": 12, "Jack": 72]newAges.forEach { name, age inprint("\(name) is \(age) years old")}let newNames = ["Jack", "Sarah", "John"]newNames.forEach { name inprint(name)}
A for-each
loop is different from a for-in
loop in that neither the break
nor the continue
statements can be used.
A while
loop executes a set of statements until a condition becomes false
. The total number of iterations are not known while executing a while
loop.
The code below shows how the while
loop is used:
import Swiftvar num = 0while num < 5 {print( "Value of number is \(num)")num = num + 1}