Looping though an array with conditionals

I am learning from the Control Flow section of a textbook and wanted to use a where clause, labeled statements, conditionals, and the continue keyword in a for-in loop.

I attempted to write an algorithm in which I print a string depending on the value of age item in an array. I only have nine items in my array, but my console is displaying 27 print statements and I don't understand why. It should only have nine strings printing to the console.

Could someone please help me to figure out how to correct this code? I'm unsure of where I erred here. I've included a screenshot of my code and the console below, as well as the actual code pasted into the body of this forum post. Please help. Thank you.

let ageArray: [Int] = [21, 17, 13, 18, 12, 9, 5, 3, 1]

teenagerContainer: for age in ageArray {

childrenContainer: for age in ageArray where age >= 6 && age <= 14 {
        print("This is a child.")
    }


if age >= 15 && age <= 18 {
    print("This is a teenager.")
}
else {
    print("This is out of the age range")
}

}

You have two loops, but you only need a single loop to get the print statements you want.

The purpose of a where clause in a loop is to restrict the number of times it runs. Because you have a loop inside of another loop, the inner code runs 9 × 3 = 27 times because the inner loop only matches 3 times instead of the 9 matches from the unrestricted outer loop.


So, to fix the code, it's probably best to just remove the inner loop and replace it with an if statement. But you're going to want to chain the three conditions together. Your textbook probably has an example of that, but if not, try to adapt your code based on this example from the Swift language guide:

if age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age >= 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

Give it try, then post back here if you're still having trouble.

2 Likes

This was really helpful, thank you for this explanation!

2 Likes