The forEach{}
method is used in Swift for the Set class to create a loop on each element of the set. It's the same as the for-in
loop. The block of the Set takes an element of the sequence as a parameter.
The syntax of the forEach{}
method is given below:
set.forEach { element in// do something with "element"}
element: This represents each element in the loop. This is passed to the block of the forEach{}
method.
The value returned is each element of the set.
Following is the example for the forEach{}
method:
// create some setslet even_numbers : Set = [10, 2, 6, 8, 4]let first_names : Set = ["john", "jane", "henry", "mark"]// print each name of the first_names setfirst_names.forEach { name inprint(name)}// print each value plus 10 of the even_numbers seteven_numbers.forEach { even inprint(even + 10)}
even_numbers
and first_names
with some values.forEach{}
method available to Set instances. We print each value of the first_name
instance to the console.even_numbers
set, but with 10
added to each value.