The forEach() method is used to iterate through each element of a set.
Example
forEach() Syntax
The syntax of the forEach() method is:
set.forEach{iterate}
Here, set is an object of the Set class.
forEach() Parameters
The forEach() method takes one parameter:
- iterate - a closure body that takes an element of the set as a parameter.
forEach() Return Value
- The
forEach()method doesn't return any value. It just iterates through the set.
Example 1: Swift set forEach()
Output
6 8 2 4 10
In the above example, we have created a set named numbers and we have used the forEach() method to iterate through it. Notice the closure body,
{ number in
print(number)
}
Here, number represents each element of numbers. And each element is printed during each iteration.
Example 2: forEach vs for Loop
Output
Using forEach(): 3 1 2 Using for loop: 3 1 2