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 setlet evenNumbers : Set = [10, 2, 6, 8, 4]// get the sequencelet sequence = evenNumbers.enumerated()for (x, y) in sequence{print(x, y)}
Explanation
- Line 2: We instantiate the
evenNumbersset 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 thesequencevariable. - Line 7: With the
for-inloop or theforloop, we are able to print each pair of the sequence to the console.