Loops in swift

In coding, when it comes to repeating operations, you can copy and paste your code 20 times or so or you can easily execute a loop.

Verify this simple example:

print("1")
print("2")
print("3")
print("4")
print("5")
print("6")
print("7")
print("8")
print("9")
print("10")
print("11")
print("12")
print("13")
print("14")
print("15")
print("16")
print("17")
print("18")
print("19")
print("20")

The console numbers 1…20 will be printed out.

I wish you didn’t actually type that every out.

This is where loops come in useful.

In Swift we can offer a collection of numbers to iterate through by using what’s called the closed range operator, which is three periods in a row.

Here’s the similar outcome with just 3 lines of code:

for i in 1...20 {
 print(i)
}

Its  right?

Let’s perform something more useful.

Looping over an array

Now were perhaps not going to do a lot of random 1…20 printing of numbers in a real world application.

But I perform guarantee you’ll require to loop over an array at some point.

So first let’s build an array:

let colorArray = ["white", "red","blue", "green", "orange", "black"]

Now let’s do a loop over this array to print out every value.

for colorBrand in colorArray {
 print(colorBrand)
 }

In your console you should observe all of the values being printed out.

That’s it!

Clearly in a real world application you wouldn’t only print things.

Inside the open and close braces, you can really perform anything.

You can perform things like conditional statements, switch statements or even more for loops within loops!


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *