For In Loop in Swift for Beginners
May 4, 2020

We use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.

Using For In loop with Simple Array:

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, (name)!")
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!

Using For In loop with Dictionary:

We can also iterate over a dictionary to access its key-value pairs.

Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated.

We can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop.

Let's take a look at example:

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("(animalName)s have (legCount) legs")
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs

In the code example below, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.

The contents of a Dictionary are inherently unordered, and iterating over them does not guarantee the order in which they will be retrieved. In particular, the order you insert items into a Dictionary doesn’t define the order they are iterated.

Using for-in loops with numeric ranges:

Foe example:

for index in 1...5 {
    print("(index) times 5 is (index * 5)")
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop. As such, index does not have to be declared before it is used. It is implicitly declared simply by its inclusion in the loop declaration, without the need for a let declaration keyword.

The sequence being iterated over is a range of numbers from 1 to 5, inclusive, as indicated by the use of the closed range operator (…).

The value of index is set to the first number in the range (1), and the statements inside the loop are executed. In this case, the loop contains only one statement, which prints an entry from the five-times table for the current value of index. After the statement is executed, the value of index is updated to contain the second value in the range (2), and the print(_:separator:terminator:) function is called again. This process continues until the end of the range is reached.

Using for-in loops with closed ranges:

In some situations, you might not want to use closed ranges, which include both endpoints.

Consider drawing the tick marks for every minute on a watch face. You want to draw 60 tick marks, starting with the 0 minute. Use the half-open range operator (..<) to include the lower bound but not the upper bound.

For example:

let minutes = 60
for tickMark in 0..<minutes {
    // render the tick mark each minute (60 times)

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

HTML Copyright SymbolHTMLHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresExplanation of PostgreSQL PgAdmin interfacePostgresHow to check if a link has http or https in it in JavaScript?JavaScriptHow to add and remove list items using JavaScript?JavaScriptWhy it’s not a good idea to create Number objects in JavaScript?JavaScript