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 sets
let even_numbers : Set = [10, 2, 6, 8, 4]
let first_names : Set = ["john", "jane", "henry", "mark"]
// print each name of the first_names set
first_names.forEach { name in
print(name)
}
// print each value plus 10 of the even_numbers set
even_numbers.forEach { even in
print(even + 10)
}

Explanation

  • Lines 2 and 3: We instantiate and initialize the sets even_numbers and first_names with some values.
  • Line 6: We use the forEach{} method available to Set instances. We print each value of the first_name instance to the console.
  • Line 11: Just like we did in line 6, we print the values of the even_numbers set, but with 10 added to each value.