Day 4 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about the different types of loops in Swift.
There are three kinds of loops in Swift. They are:
- For loop
- While loop
- Repeat loop
1.For loop are used to repeat an action a certain number of times. For example, You can use it to pass through an array
let names = ["Kaladin","Jasnah Kholin", "Adolin Kholin", "Shallan", "Syl", "Maosh", "Szeth-son-son-Vallano"]
for names in names {
print(name)
}
let numbers = [1,2,3,4,5]
for number in numbers {
print(numbers)
}
for _ in 1...5 {
getData()
}
The first code above will print a list of characters from Stormlight Archives. The second code prints the number one through five. The third executes getData()
five times. Please note, in the third example, we used _
because we don't need the number being created by the for-loop.
2.While loops are used to perform an action an unlimited number of times until a condition is met. You should use while loops when you repeat a code until something changes. For example, a while loop is written like this in Swift.
let number = 1
while number <= 5 {
getData()
}
The code above executes getData()
until number
becomes greater than 5. So basically, it executes getData()
five times.
3.Repeat loops are very similar to while loops. The only difference is that repeat loops run the code first before checking if the condition has been met. In while loops, the code condition is checked first before running the code.
let number = 1
repeat {
getData()
} while number <= 5
Swift also has two features for controlling the flow within loops. They are the break
and continue
.
With the break
keyword you can stop the execution of a loop.
For example, this is how you would use the break
in swift
let numbers = [1,2,3,4,0,5,20,2]
for number in numbers {
if number == 0 {
print("number should not be zero")
break
}
print(number)
}
The code above runs through an array of numbers but checks if a number is zero. If a number is zero, it stops the for-loop entirely. That means the code would print numbers 1,2,3,4
only.
With the continue
keyword you can skip the execution for a particular loop. For example, this is how you would use the continue
in swift
let numbers = [1,2,3,4,0,5,20,2]
for number in numbers {
if number == 0 {
continue
print("number should not be zero")
}
print(number)
}
The code above also runs through an array of numbers but checks if a number is zero. If a number is zero, it skips that particular loop. That means the code would print numbers 1,2,3,4,5,30,2
only. Ignoring zero and also the print statement after the continue
If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)
Top comments (0)