Swift programming for Beginners – Swift for-in Loop

(Swift for Beginners)

Swift for-in Loop

In this article, you will learn about for-in loop, its use cases and variants.

For-in loops are used to run a set of tasks for a certain number of times. These loops iterate over any sequences such as items in an array, range, or characters in a string.

We also use for-in loop to do some repetitive processes for a fixed amount of time.


Why do we need for-in loop?

Imagine someone told you to write a program that outputs Hello, World! in the screen. Your solution will be:

print("Hello, World!")

What if, they changed their mind and told you to write a program that outputs Hello, World! in the screen for five times..Without the knowledge of loop, your solution might be:

print("Hello, World!")
print("Hello, World!")
print("Hello, World!")
print("Hello, World!")
print("Hello, World!")

Hmm. Looks time consuming to write similar code for five times to accomplish same work. If so, what would you do if someone request you to write a program that outputs Hello, World! in the screen for hundred or even million times?

One naive solution is to write the print statement for given number of times. Sounds crazy, right? But there is a better solution for this with the use of for-in loops with few lines of code as:

for i in 1...100 {
	//outputs Hello world for 100 times in the screen
	print("Hello, World!")
}

Don’t worry about the syntax, we are going to explore it below.


For-in Loop syntax

You can create a for in loop in Swift as:

for <value> in <range> {
	<some work here>
}

The above loop iterates over a range and we can access each element returned from the range in <value> variable. If you don’t know about range, you can check the article: Swift Ranges.


How it works?

  • The sequence being iterated over is a <range>.
  • The <value> is set to the first number in the range , and the statements inside the loop <some work here> are executed.
  • After the statement is executed, the <value> is updated to contain the second value in the <range> and the statement <some work here> is executed again.
  • This process continues until the end of the range is reached and the loop stops.

 

Example 1 : How for-in loop works in Swift

for i in 1...3 {
	print("Hello world!. Value is (i)")
}

When you run the program, the output will be:

Hello world!. Value is 1
Hello world!. Value is 2
Hello world!. Value is 3

In the above program, the sequence being iterated over is a range from 1 to 3.

The value of i is set to the first number in the range (1), and updated to the next number of the range on each iteration. This process continues until the end of the range (3) is reached.

For-in loop execution steps
Iteration Value returned from range (i) Output
1 1 Hello world!. Value is 1
2 2 Hello world!. Value is 2
3 3 Hello world!. Value is 3

Discarding the range value in a for-in loop

If you have no use for the range value inside the loop, you can discard using _ (underscore) in Swift as:

for _ in <range> {
	<some work here>
}

Example 2: Discarding range value in for-in loop

// This example neglects value and uses half open range operator
for _ in 1..<3 {
	print("Hello world!")
}

When you run the program, the output will be:

Hello world!
Hello world!

In the above program, the sequence being iterated over is a range from 1 to 2 because of the use of half-open range operator (..<) which includes the lower bound(1) but not the upper bound(3).

_ neglects the value from the range (1) and the print statement is executed. The print statement is called again for next iteration and the process ends because 2 is the last value in the range.

For-in loop execution steps without range values
Iteration Value Returned from Range Output
1 Discarded Hello world!
2 Discarded Hello world!

for-in loop for fixed intervals using stride

If you want a loop that increments by some fixed value in each iteration, instead of range, you have to use stride method.

Example 3: for-in loop using stride method

let interval = 2
for i in stride(from: 1, to: 10, by: interval) {
	print(i)
}

When you run the program, the output will be:

1
3
5
7
9

In the above program, the stride function returns the sequence of numbers: 1, 3, 5, 7, 9.

The value of i is set to the first number of the sequence (1), and the print statement inside the loop is executed which outputs “1” in the console.

After the statement is executed, the value of i is updated to another value (3) and the print statement is called again. This process continues until all the elements of the sequence is accessed.

For-in loop execution steps using stride
Value Condition (Value < End) i (Output)
1 1 < 10 (true) 1
1 + 2 = 3 3 < 10 (true) 3
1 + 2 * 2 = 5 5 < 10 (true) 5
1 + 3 * 2 = 7 7 < 10 (true) 7
1 + 4 * 2 = 9 9 < 10 (true) 9
1 + 5 * 2 = 11 11 < 10 (false) Stops

How to access elements of a collection using for-in loop?

Suppose you have an array of strings as below. If you don’t know about array, think of array as a single container that can store more than one values. For more detailed explanation, see Swift Arrays.

let programmingLanguages = ["Swift", "Java", "Go","JavaScript","Kotlin","Python"]

What if someone told you to print all the programming languages?

A way is to access those elements using index as programmingLanguages[0], programmingLanguages[1] … and so on till you get all the elements. But this is too tedious.

Here comes for-in loop to the rescue. You can iterate using for in loop as:

Example 4: Accessing elements of an array (collection) using for-in loop

let programmingLanguages = ["Swift", "Java", "Go", "JavaScript", "Kotlin", "Python"]
for language in programmingLanguages {
      print(language)
}

When you run the program, the output will be:

Swift
Java
Go
JavaScript
Kotlin
Python

In the above program, the sequence being iterated over is an array of strings.

The value of language is set to the first element of the array, and the print statement inside the loop is executed which outputs “Swift” in the console.

After the statement is executed, language is updated with the next element of the array and the print statement is called again. This process continues until the last element of array is accessed.


Example 5: Accessing elements of a string (collection) using for-in loop

Since, in Swift, strings are also collection, you can access each character in a string using for loop.

for value in "I♥Swift!" {
	print(value)
}

When you run the program, the output will be:

I
♥
S
w
i
f
t
!

How to access indices of a collection using for-in loop?

If you want to access the index of the array (position of elements in an array i.e. 0, 1, 2), you need to use enumerated method as:

Example 6: Accessing indices of an array using for-in loop

let programmingLanguages = ["Swift", "Java", "Go", "JavaScript", "Kotlin", "Python"]
for (index, language) in programmingLanguages.enumerated() {
      print("(index):(language)")
}

When you run the program, the output will be:

0:Swift
1:Java
2:Go
3:JavaScript
4:Kotlin
5:Python

Here, the enumerated method returns a tuple (IntString) composed of the index (Int) and the value (String) for each item in the array. For example: (0, Swift), (1, Java)…

Using for-in loop, you can access these items in a tuple one by one. If you don’t know about Tuple, you can simply think it as a container that can hold value of different types. For more detailed explanation, see Swift Tuples.


How to filter elements using where clause in a for-in loop?

You can also filter contents from for in loop using where clause as

for value in "I♥Swift!" where value != "!" {
	print(value) //removes exclamation sign
}

When you run the program, the output will be:

I
♥
S
w
i
f
t

In the above program, the sequence being iterated over is string (collection of characters).

value is set to the first character of the string and is checked with the where condition. If the condition returns true, the block inside the loop (print statement) is executed which outputs “I” in the console.

After the statement is executed, value is updated to next character of the string and again condition is checked. If the condition returns false, it does not execute the block and value is updated to next character.

This process continues until the last character of the string is accessed.

Filter using for-in loop execution steps
Iteration value value != “!” Output
1 I true I
2 true
3 S true S
4 w true w
5 i true i
6 f true f
7 t true t
8 ! false

 

Swift programming for Beginners – Swift for-in Loop

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!