The forEach()
method is used to iterate through each element of a dictionary.
Example
var information = ["Charlie": 54, "Harvey": 38, "Donna": 34]
// use forEach() to iterate through a dictionary
information.forEach { info in
print(info)
}
// Output:
// (key: "Harvey", value: 38)
// (key: "Donna", value: 34)
// (key: "Charlie", value: 54)
forEach() Syntax
The syntax of the forEach()
method is:
dictionary.forEach{iterate}
Here, dictionary is an object of the Dictionary
class.
forEach() Parameters
The forEach()
method takes one parameter:
- iterate - a closure body that takes an element of the dictionary as a parameter.
forEach() Return Value
- The
forEach()
method doesn't return any value. It just iterates through the dictionary.
Example 1: Swift Dictionary forEach()
// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]
// use forEach() to iterate through a dictionary
information.forEach { info in
print(info)
}
Output
(key: "Carlos", value: 1999) (key: "Judy", value: 1992) (key: "Nelson", value: 1987)
In the above example, we have created a dictionary named information and we have used the forEach()
method to iterate through it. Notice the closure body,
{ info in
print(info)
}
Here, info represents each element of information. And each element is printed during each iteration.
Example 2: Iterate through all keys
// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]
// iterate through all the keys
information.keys.forEach { info in
print(info)
}
Output
Carlos Judy Nelson
Here, we have used the keys
property to iterate through all the keys of the information dictionary
information.keys.forEach {...}
Example 3: Iterate through all values
// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]
// iterate through all the values
information.values.forEach { info in
print(info)
}
Output
1999 1987 1992
Here, we have used the values
property to iterate through all the values of the information dictionary
information.values.forEach {...}