The forEach()
method is used to iterate through each element of a set.
Example
var information: Set = ["Charlie", "Harvey", "Donna"]
// use forEach() to iterate through a set
information.forEach { info in
print(info)
}
// Output:
// Charlie
// Donna
// Harvey
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()
// create a set numbers
var numbers: Set = [2,4,6,8,10]
// use forEach() to iterate through a set
numbers.forEach { number in
print(number)
}
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
// create a set numbers
var numbers: Set = [1,2,3]
print("Using forEach():")
// use forEach() to iterate through a set
numbers.forEach { number in
print(number)
}
print("Using for loop:")
// use for loop to iterate through a set
for number in numbers {
print(number)
}
Output
Using forEach(): 3 1 2 Using for loop: 3 1 2