Swift Dictionary enumerated()

The enumerated() method is used to iterate through key-value pairs of a dictionary.

Example


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()

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

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.