Swift Dictionary forEach()

The forEach() method is used to iterate through each element of a dictionary.

Example


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

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

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

Output

1999
1987
1992

Here, we have used the values property to iterate through all the values of the information dictionary

information.values.forEach {...}