YogeshChauhan . com

For In Loop in Swift for Beginners

in Swift on 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)
}
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to display modal from bottom to top using CSS and JavaScript?CSS5 Ways to Loop Through JavaScript ArraysJavaScriptHow to convert an object from API to JSON array in Angular 9?AngularObject destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptClasses in JavaScript: The BasicsJavaScriptHow to create a vertically rotating texts using CSS?CSS