How To Use Every Swift Loop (For, While, Repeat)

Swift loops allow us to repeat a block of code. Learn how to use all the types of Swift loops with this guide!

Continue Reading…

Written by

Chris C

Published on

22 Nov 2019

Swift For Loop

Sometimes during programming we sometimes come upon a task that has to deal with huge amounts of data, It could be a list of 20 items or maybe even 2000.

You might think to yourself, is there a way to make my job easier so that I don’t have to type everything out manually? Surely it would take a lot of time to type everything manually, not to mention all the resources it will use.

This is where loops come into play. 

What is a Swift Loop?

A loop or iterator to put simply, lets you describe repetitive processes. It could have a fixed amount of steps or It could have an unknown/dynamic number of steps. There are quite a few ways to tackle loops in swift and this article will help you familiarize yourself with them.

The Basics

Swift While Loops

This is probably one of the most basic and known loops. A while loop performs a set of statements until a condition becomes false. The syntax is as follows:

while [condition] {
	[code to perform]
//note that most cases the statements usually lead to not fulfilling the condition in order to break the loop
}

The loop will repeat the code as long as the condition is true. A small demonstration to explain better how it works, here is a code that will add a series of numbers to itself until it reaches a fixed number of times (let’s say 10).

var i:Int = 1
var sum:Int = 0

while i < 10 {
    sum = sum + i //it’s like we did 1+2+3+4+5+6+7+8+9!
    i+=1
}

print(sum) //prints 45

Based on this example we can clearly see the usefulness of using the while loop in Swift. 

Swift Repeat – While Loops

Similar to the while loop this will execute the codes that you set and will exit the loop once the condition is not fulfilled. However, the main difference is that the while loop starts with a condition check first before it does the statements. Thus, the codes you set might not be executed at all if the condition has already been fulfilled. For example in a while loop:

var i:Int = 1
var runLoop:Bool = false
var sum:Int = 0

while runLoop {
    sum = sum + i; //it’s like we did 1+2+3+4+5+6+7+8+9!
    i+=1;
}

print(sum) //prints 0

BUT, if we ran the same code in a repeat – while loop then:

var i:Int = 1
var runLoop:Bool = false
var sum:Int = 0

repeat {
    sum = sum + i; //it’s like we did 1+2+3+4+5+6+7+8+9!
    i+=1;
} while runLoop

print(sum) //prints 1

As you can see it ran the code at least once instead of ignoring it, it might be extremely useful in some cases where you need to at least display one result instead of nothing. 

Warning: Be careful when using this loop as it will crash your program when you work with empty arrays and you try to reference a non-existing index of an array.

Swift For – In Loops

The For loop is probably the most popular and widely used loop in swift. This is because it has a built-in “index” which makes going through data fast and easy.

The syntax of a For – In loop is as follows:

for [variable name] in [range]{
//codes to execute
}

For example, if we were to translate our code earlier it would be written as:

var sum:Int = 0

for i in 1...9 {
    sum += i  //it’s like we did 1+2+3+4+5+6+7+8+9!
}

print(sum) //prints 45

As per example we can clearly see that the code is much cleaner, first off we didn’t need to declare i at the start. Then, we didn’t need to increment i (i+=1) because it did it for us using a range of values from 1 – 9 [1,2,3,4,5,6,7,8,9].

For – In’s usefulness doesn’t stop there though. It can also be used to iterate through arrays and dictionaries easily!. Let’s give arrays a try shall we:

let codewithchristeam = ["Chris", "Ellen", "Francis", "Katrina", "Adrien", "Arthur"]

for name in codewithchristeam {
    print("Hello, \(name)!")
}
// prints out:
// Hello, Chris!
// Hello, Ellen!
// Hello, Francis!
// Hello, Katrina!
// Hello, Adrien!
// Hello, Arthur!

Isn’t that great? Super efficient and very easy to use for sure. Lets try the dictionary then:

let fruitmarket = ["banana": 1.5, "apple": 3, "mango": 5]

for (fruitName, price) in fruitmarket {
    print("\(fruitName) is \(price) per piece")
}

	//prints out
	//apple is 3.0 per piece
//banana is 1.5 per piece
//mango is 5.0 per piece

Amazing! the same logic and the same ease of usage. No wonder its popular right? 🙂

Built – In Loops

Swift has a lot of useful features that make coding fast and easy and putting built in loops in variables is one of them. 

Take for instance the ever popular Array, bet you didn’t know it actually has a built-in function to let you loop through data instantly. (not that the For – In loop can’t solve that

forEach{ [element] -> Void } – iterates over the array and does specified commands to it

let codewithchristeam = ["Chris", "Ellen", "Francis", "Katrina", "Adrien", "Arthur"]

//the for - in code
for name in codewithchristeam {
    print("Hello, \(name)!")
}

	//the built-in foreach code of the array

codewithchristeam.forEach { name in
    print("Hello, \(name)!")
}

// both of them prints out:
// Hello, Chris!
// Hello, Ellen!
// Hello, Francis!
// Hello, Katrina!
// Hello, Adrien!
// Hello, Arthur!

Similarly, this built-in function also works in Dictionaries!

let fruitmarket = ["banana": 1.5, "apple": 3, "mango": 5]

for (fruitName, price) in fruitmarket {
    print("\(fruitName) is \(price) per piece")
}

fruitmarket.forEach { (fruitName, price) in
    print("\(fruitName) is \(price) per piece")
}

//both prints out
	//apple is 3.0 per piece
//banana is 1.5 per piece
//mango is 5.0 per piece

As you can see Swift has made looping through data easier than ever and in turn encourages those who are new to coding not be intimidated by huge amounts of data because at the end of the day, a loop is all you might need 🙂


Further Reading

  • The Complete Swift Tutorial for Beginners: Learn Swift programming with my Swift guide designed with the beginner in mind.
  • Swift Guard Statements: A guard statement is as simple as using an if..else statement and has its own benefits and uses. Learn how to use Swift guard statements in this tutorial!
  • Swift Enum: Swift enums allow us to define a set of values that the enum can take on. Learn how to use it with this tutorial!
  • 7 Day App Action Plan: Plan out your app and finally get started turning your app idea into reality.

Table of contents
    0 Shares
    Share
    Tweet
    Pin
    Share
    Buffer