What is the Set.enumerated() function in Swift?

Overview

The Set.enumerated() function in Swift returns a sequence of (index, value) pairs of a set. The index represents an element from a series of consecutive integers starting at zero. The value represents an element in the set.

Syntax

set.enumerated()
The syntax for the enumerated() function in Swift

Parameters

This function takes no parameters.

Return value

The value returned is an enumerated sequence containing pairs of index and elements of a set. The first value of the pair represents the element's index. Its second value represents the element itself.

Example

// create a set
let evenNumbers : Set = [10, 2, 6, 8, 4]
// get the sequence
let sequence = evenNumbers.enumerated()
for (x, y) in sequence{
print(x, y)
}

Explanation

  • Line 2: We instantiate the evenNumbers set and initialize it with some values.
  • Line 3: We use the enumerated() function to get an enumerated sequence of pairs. We store the result inside the sequence variable.
  • Line 7: With the for-in loop or the for loop, we are able to print each pair of the sequence to the console.

Free Resources