For-In Loops

In Swift language we use the for-in loop to iterate over a sequence. A sequence contains items such Array elements, Ranges of numbers or Characters in a String for example.

Let’s quickly experiment with some code. You can iterate a genres of music Array like this for example:

// Iterate genres
let genres = ["Ambient", "Dubstep", "Electronic", "Hip Hop", "Jazz"]
print("Choose a genre:")
for genre in genres {
  print("\(genre)")
}

As we can see, we iterated over an Array printing every genre inside. We can go further and try the same using a Dictionary insted of an Array.

Now we have music titles with a file type.

// Iterate dictionaries
let titleWithAudioTypes = ["Castle in the Hill": "MP3", "Different seas": "WAV", "See you again": "FLAC"]
for (title, audioType) in titleWithAudioTypes {
  print("\(title).\(audioType.lowercased())")
}

Above, each item in the Dictionary is returned as (key, value) pairs.

Now let’s say that we want to put a sound to repeat five times. You could use for-in loops with numeric Ranges to achieve this.

// Iterate ranges
let soundTitle = "See you again.mp3"
let soundRepeats = 5
for time in 1...soundRepeats {
  print("Repeating \(soundTitle): \(time) time(s)")
}

The key here is the closed Range operator (...). Most of the times when you don’t need the constant inside the loop, for example time in for time in (...) you can ignore the values by using an underscore _ in place of a variable name. time it’s implicity declared by its inclusion in the loop declaration.

You can read more about for-in loops in Swift on Apple Swift Book.