W1155 For Loop in Collection Types

From Coder Merlin
Jump to navigation Jump to search
Radar Antenna Array



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 {

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 {

Key Concepts[edit]



CoderMerlin™ proudly recommends:

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!

Designed with pride in Silicon Valley, CA, USA