Line At A Time
Lesson 16: For-in Loops
For-in Loops Visit every item in an array, one by one.
1let fruits = ["apple", "banana", "cherry"]
2for fruit in fruits {
3 print(fruit)
4}
Terminal
$ swift main.swift
apple
banana
cherry
Every line, explained
let fruits = ["apple", "banana", "cherry"]
An array stores several values in one variable. The values go between square brackets, separated by commas.
for fruit in fruits {
for ... in visits each item, one trip around the loop per item. Each time, the loop variable holds the current item. Naming the loop variable fruit (singular) and the array fruits (plural) makes it read like English: "for each fruit in fruits".
print(fruit)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Runs three times, once per item, and fruit is different each time.
}
This } closes the for loop.