What is set.forEach{} in Swift?
Overview
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.
Syntax
The syntax of the forEach{} method is given below:
set.forEach { element in// do something with "element"}
Syntax for set.forEach{} method in Swift
Parameter
element: This represents each element in the loop. This is passed to the block of the forEach{} method.
Return value
The value returned is each element of the set.
Example
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)}
Explanation
- Lines 2 and 3: We instantiate and initialize the sets
even_numbersandfirst_nameswith some values. - Line 6: We use the
forEach{}method available to Set instances. We print each value of thefirst_nameinstance to the console. - Line 11: Just like we did in line 6, we print the values of the
even_numbersset, but with10added to each value.