Yogesh Chauhan's Blog

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)

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to Create a Backup From Any Database in SQL?SQL/MySQLWordPress: How to loop through ACF group fields?WordPressWhen you don’t want to @forward every member in SCSS (Sass)SCSSHow to apply style to a specific child element using CSS?CSSThe Difference Between Arrays and Objects in JavaScriptJavaScriptHow to change CSS with jQuery?CSS