Start learning free

LESSON 106 OF 349 · FOR LOOPS - LOOPING OVER ARRAYS

For Loops in Swift in Swift

Lesson

A for loop is a special type of loop in Swift which allows us to loop over the items of a collection, such as an array.


Looping through an array:

For example, an array is a sequence of items, so we can use a for loop to iterate over each item and do something with it:

let fruits = ["banana", "orange", "pear", "kivi"]

for fruit in fruits {
  print("I eat \(fruit)")
}

The output of this code is:

I eat banana
I eat orange
I eat pear
I eat kivi

Let's break down this code:

  • The for keyword that indicates the start of a for loop.
  • fruit is the loop variable. It will take the value of each different item in the collection
  • The in keyword separates the loop variable from the collection we will iterate on
  • fruits is the collection to loop over

Assignment
Now let's greet our friends using a for loop!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    Looping Through Arrays in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free