Workshop 21: The for and for-in Loop

In this workshop you learn how to us the for and for-in loop to iterate over elements in an array variable. You also learn to iterate over entries in a dictionary array variable.

Before you begin, I assume you have done the following:

workshop16-fig00

The for and for-in Loop

The Swift for and for-in loop execute a block of code a certain number of times. They are perfect tools for iterating over elements in an array, or entries in a dictionary.

Iterating Over an Array Variable

Code below demonstrate how to use the for and for-in loop to iterate over an array variable.

// Declare and initialize an array variable
var sounds = ["bark", "Meow", "Moo", "Neigh", "Roar"]
for var i=0; i < sounds.count; i++ {
  // Display the array elements
  println(sounds[i])
}
// print a blank line
println()

for sound in sounds {
  // Display the array elements
  dump("\(sound)! Hey, be quit!")
}
Output

Code in the  for and for-in loop block display this output in the playground file’s Timeline panel.

bark
Meow
Moo
Neigh
Roar

– bark! Hey, be quit!
– Meow! Hey, be quit!
– Moo! Hey, be quit!
– Neigh! Hey, be quit!
– Roar! Hey, be quit!

Iterating Over a Dictionary Constant

// Declare and initialize a dictionary constant
let animalSound = ["Dog": "bark",
    "Cat": "meow",
    "Cow": "moo",
    "Horse": "neigh",
    "Lion": "roar"]

for (key, value) in animalSound {
    // Display the dictionary key-value pairs
    println("\(key), \(value)")
}
Output

Code in the for-in loop block display this output in the playground file’s Timeline panel.

Lion, roar
Cat, meow
Dog, bark
Cow, moo
Horse, neigh