W1155 For Loop in Collection Types

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Radar Antenna Array

Prerequisites[edit]

Introduction[edit]

We've seen how for loops can be used to iterate over an integer range but for loops are actually much more flexible and can be used to easily iterate over many collection types. We'll learn more about collection types soon. In this experience, we'll take a look at how for loops can iterate through a string.

The String[edit]

Strings are a type of collection. Collections can be thought of as a container which holds zero or more elements of a type. In the case of strings, each element is a Character.

Iteration Over a String[edit]

Just as we can iterate over a range, we can iterate over strings. In both cases, the syntax is very similar.

let fruit = "Apple"
for character in fruit {
    print(character)
}

Or, a slightly more complex example:

func isItP(character:Character) {
    if character == "p" {
        print("It's p!")
    } else {
        print("It's not p; it's \(character).")
    }
}

let fruit = "Apple"
for character in fruit {
    isItP(character:character)
}

Key Concepts[edit]

Exercises[edit]

References[edit]