Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

How to create loops in Swift

Mohammad Razi ul Haq

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:

  • the code to execute
  • the condition that needs to hold true for the loop to execute

Swift has multiple kinds of loops such as:for-in, for-each, and while loops for repeated execution of a set of statements.

For loop

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.

Flowchart of a for loop

The code below shows how the two kinds of for loopsfor-in loop and for-each loop can be used:

import Swift

// For-in loop
let 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 loop
print("\n Using the for each loop \n")

let newAges = ["John": 28, "Sarah": 12, "Jack": 72]
newAges.forEach { name, age in
    print("\(name) is \(age) years old")
}

let newNames = ["Jack", "Sarah", "John"]
newNames.forEach { name in
    print(name)
}

A for-each loop is different from a for-in loop in that neither the break nor the continue statements can be used.

While loop

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 Swift

var num = 0

while num < 5 {
  print( "Value of number is \(num)")
  num = num + 1
}

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Mohammad Razi ul Haq
RELATED COURSES

View all Courses

Keep Exploring