The enumerated()
method is used to iterate through key-value pairs of a dictionary.
Example
var information = ["Charlie": 54, "Harvey": 38, "Donna": 34]
// use enumerated() to iterate through a dictionary
for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)")
}
// Output:
// 0: (key: "Donna", value: 34)
// 1: (key: "Charlie", value: 54)
// 2: (key: "Harvey", value: 38)
enumerated() Syntax
The syntax of the enumerated()
method is:
dictionary.enumerated{iterate}
Here, dictionary is an object of the Dictionary
class.
enumerated() Parameters
The enumerated()
method takes one parameter:
- iterate - a closure body that takes an element of the dictionary as a parameter.
enumerated() Return Value
- The
enumerated()
method returns a sequence of key-value pairs with their index values.
Example 1: Swift Dictionary enumerated()
// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]
// use enumerated() to iterate through a dictionary
for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)")
}
Output
0: (key: "Judy", value: 1992) 1: (key: "Nelson", value: 1987) 2: (key: "Carlos", value: 1999)
In the above example, we have created a dictionary named information and we have used the enumerated()
method to iterate through it. Notice the use of for
and enumerated()
method,
for (index, key_value) in information.enumerated() {
print("\(index): \(key_value)")
}
Here, index represents the index value of each key-value pair and key_value
represents each key-value of information.
Example 2: Access Only Key-Value Pairs
// create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]
// use enumerated() to iterate through a dictionary
for (_, key_value) in information.enumerated() {
print("\(key_value)")
}
Output
(key: "Nelson", value: 1987) (key: "Carlos", value: 1999) (key: "Judy", value: 1992)
In the above example, we have used the enumerated()
method to iterate through key-value pair. Notice the line,
for (_, key_value) in information.enumerated() { ... }
Here, we have used underscore _
instead of the variable name to iterate through key-value pairs without their index value.