What Are “For Loops”? | Swift Basics Tutorial

iOS tutorial SWIFT For Loops featured photo

In this iOS tutorial SWIFT For Loops, we’re going to show you what for loops are and how to use them through some great examples.

Different types of “For Loops”

For loops grant us the ability to run code multiple times. There are two types of for loops that we use in everyday programming:

  1. For-condition-increment loops
    Basically, these types of for loops make the code run until the condition is met. With this type, you are able to increment a counter which will have the loop execute until the counter reaches a certain value.
  2. For-In loops
    This type of loop is associated with fast enumeration. You can use this to iterate numbers in a range.

For-condition-increment loop

In the next example you will see how to use a for-condition-increment loop to make the console return “Hi there” for a total of 10 times.

for i = 0; i < 10; i++
    print("Hi there")


For-in loop

Here is an example of a for-in loop:

class Shoe {}
var shoes = [Shoe]()
for i in 1...4
print("We have \(shoes.count) shoes!")

We do many things in the above code, so I’ll break it down.

  • First, we create a class called Shoe.
  • We then create an array called shoes.
  • In the loop, we state that for every time the code executes, we add an object to our array. So the console will say that we have 4 shoes.

Declarations And For Loops

Here we can see a type of declaration where we use type inference to assume that each object in an array of type [Shoe] will be a Shoe:

for shoe in shoes
    //Do stuff here

And here is how we declare it as type “Shoe” explicitly:

for shoe:Shoe in shoes
    //Do something here

Let’s consider the following:

struct Person
    var health:Int = 1
var person1 = Person()
var person2 = person1
person2.health = 2

So, if we run this code the value of person1.health will be 1 and the value of person2.health will be 2. This is because structures in Swift are value types. Classes instead are reference types. If the example above were a class, then both objects would have their “health” property value equal to “2”. Remember, structures are copied by value rather than reference.

In conclusion, if you liked this iOS tutorial SWIFT For Loops, take a look at some of our other stuff at the tutorial section.

Recommended for you [SWIFT] How to add In-App Purchases in your iOS app

Leave a Reply

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