Game Development Reference
In-Depth Information
for-in
The for-in version of the for loop is most useful when you are iterating over a com-
plete collection of values or when you want to iterate over a range of values in a collec-
tion. Take a look at the following loop:
var colors = ["red", "blue", "green", "black", "blue",
"orange"]
for color in colors {
println("The color is : \(color)")
}
This loop does exactly what the previous for loop did, but look at how much simpler this
version is. This loop iterates over the colors array assigning each element to the color
variable and then prints the value in color. You are iterating over the entire collection,
which means you don't care about a conditional.
If you want to iterate over only part of this array, you can use a range. You represent a
range in Swift using three dots ( ... ) following the in part of the for loop.
var colors = ["red", "blue", "green", "black", "blue",
"orange"]
for index in 2...4 {
println("The color is : \(colors[index])")
}
This loop will print the values only in the third, fourth, and fifth positions of the colors
array.
The for-in loop has a really cool feature for iterating over dictionaries.
var states = ["CO":"Colorado", "UT":"Utah", "NM":"New
Mexico"]
for (abbreviation, state) in states {
println("The abbreviation for \(state) is
\(abbreviation)")
}
This code begins by creating a dictionary with state abbreviations as the keys and the state
names as the values. Then the for-in loop iterates over the dictionary assigning the two
variables surrounded by parentheses each key-value pair found in each element of the dic-
Search WWH ::




Custom Search