Swift Loops: For & While Loop, Break & Continue in Loops

Swift Loops: For & While Loop, Break & Continue in Loops

ยท

6 min read

Hi All, As I told in the previous articles that I have started a #100DaysOfSwiftUI challenge this is my learning from Day 6. where I have learned about Loops in Swift and different types of loops offered by Swift. Let's go through it at once:

Loops

Computers are great at doing repetitive work which we tend to avoid as humans. Loops are one of the things that help you in repeating a task as many times as you. it can be from once to billion-time repetitions (Don't try to run something a billion times though ๐Ÿ˜… anything can happen, but if you do something like that do let me know the result ๐Ÿ˜‚)

There are 2 types of loop in swift i.e For and While loops. The For loops are used when you know for sure that how many times you want to repeat your task run And when you don't know that how many times you may have to run a task to get your required result then you will use the While loop.

For Loop To Repeat Work

In Swift, it is easy to repeat some tasks for the fixed times for each entry in an array, set, or Dictionary using a For loop.

Let's start with a simple loop through array:

let platforms = ["iOS, "macOS", "tvOS", "watchOS"]

for os in platform {
    print("Swift works on \(os).")
}

So using the for loop we are going through each item in the platform array and printing them saying swift works on that platform. let's break things up on how for loop is written:

  • first is for which tells swift that we are using a for loop in code.
  • Second is the variable name to which we are going to assign the items in the array one by one so that we can those values inside the loop Which can be anything.
  • then word in tells the next is the name of the data collection we can get the values from.
  • then the name of the array from which we are going to get the values.
  • then we give some lines of code which will be executed for every item in that array. The code be executed in the loop is placed inside curly brackets { } so Swift can know what the code is to run in a loop which can be called as loop body.

as you can see in the above code snippet we are reading values one by one from the platform array and assigning it to os variable then inside the loop body printing the message that swift works on that OS.

Also, that loops are not only used to loop over arrays we can use them to run some code for the number of iterations we want. like this:

for i in 1...10 {
    print("5 x \(i) is \(5 * i)")
}

for _ in 1..<5 {
    print("Hello world!")
}

So as we can see in the code snippet that we are creating the 5's table using for loop where I tell us that which iteration we are running and in place of the array we provided last time we provide a range that is 1...10 so this means all the variables between 1 to 10 and also include 1 and 10, as we can see in the second for loop I have provided range as 1..<5 which means that all the number between 1 and 5 and also include 1 but not number 5.

Also in place of the variable name in the second for loop I am placing _ which is offered by swift when we not using some variable then we can give the name of that variable as - and in our, for loop, we are not using those numbers so we don't need to define any variables.

We will be using for loops more in the future we will get to know more about these as we go thorough.

While Loop To Repeat Work

Unlike the For loop which repeats for a fixed number of times, the While loop can run an infinite number of times. as long as the provided condition is true, the while loop will keep running.

Here's how the While loop works:

var countdown = 5

while countdown > 0 {
   print("\(countdown)...")
   countdown -= 1
}

print("Blast off!!")

So in while will be defined like this:

  • we begin with while to indicate Swift about while loop
  • a condition loop will be executed until the condition become false (Keep in mind while creating the condition which should not such way that condition will not become false then you will be having an infinite loop in your hand ๐Ÿ˜…)
  • finally loop body you should mention all the code to be executed in the loop inside which is placed inside curly brackets.

the main difference is that for loops are generally used with finite sequences: we loop through the numbers 1 through 10, or the items in an array for example. on the other hand, while loops can loop until any arbitrary condition becomes false which allows them until we tell them to stop. and for example: if we want to roll a 6 on dice then we won't be knowing beforehand how many tries it will take us to get 6 there to create a while loop and set conditions that will become false when we get 6 on a dice roll.

Skip Loop Items With Break And Continue

Regardless of what loop we use, Some times we want to end our loop prematurely or we want to skip the loop iteration for one of the items then we have Break and Continue in swift in which break will stop the loop run completely and continue will just skip the iteration and continue to execute the loop till the end.

Skip Loop Iteration Using Continue

when we call continue inside the loop body, Swift will immediately stop executing the current loop iteration and jump to the next item in the loop where it will carry on as normal. this is the command used near the start of loops, where you eliminate the loop variable that doesn't pass the test of your choosing.

Here's an example:

let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"]

for filename in filenames {
    if filename.hasSuffix(".jpg") == false {
        continue
    }

    print("Found picture: \(filename)")
}

So using the continue we can skip the print when we don't have the .jpg files and print only the .jpg files.

Stop Loop Using Break

As for Break, that exits the loop immediately and skips all remaining iterations. To demonstrate this here's an example:

let number1 = 4
let number2 = 14
var multiples = [Int]()

for i in 1...100_000 {
    if i.isMultiple(of: number1) && i.isMultiple(of: number2) {
        multiples.append(i)

        if multiples.count == 10 {
            break
        }
    }
}

print(multiples)

So in the code, above we are creating 2 variables to hold numbers. and integer array to store the multiples of our two variables created. then using the for loop for the range 1 to 100,000 and inside the loop, we are adding the value to the integer array we created when the number is multiple of both numbers we created. and continue the loop until the number of items in the integer array hit's number 0 then using break we stopping the loop run immediately and exiting the loop.

Conclusion

So I have learned on the Day 6 of 100 Days of SwiftUI that how to use Loops in the Swift which are for and while loop. and use case of both. Then use of continue and break to stop the loop execution and use cases for both.

Also, let me know if any mistakes are done in this blog/write-up I have done on Day 6 learning so I can fix my mistakes and improve my understandings.

Thank you.