What is the Set.startIndex property in Swift?

Overview

A set contains unique values. It does not accept duplicates. The startIndex property of a set instance returns the index position or the starting position of the set members during the iteration. In other words, it is the index of the first members of a set when it is looped.

Note: When the set is looped or iterated, the order of the values is not taken into consideration. Hence, the startIndex, when accessed on the class, returns different values for every execution.

Syntax

set.startIndex
Syntax of startIndex Property of a Set

Return value

The value returned is an index type.

Example

// create some sets
let evenNumbers : Set = [10, 2, 6, 8, 4]
let oddNumbers : Set = [11, 5, 7, 3, 9]
let first_names : Set = ["john", "jane", "henry", "mark"]
// get set value with position as startIndex
print(type(of :evenNumbers.startIndex))
print(oddNumbers[oddNumbers.startIndex])
print(first_names[first_names.startIndex])

Explanation

  • Line 2–4: We create set values and initialize them.
  • Line 7–9: We access the startIndex of the set instances and print the values to the console. Note that the value changes at every execution. This is because during any iteration, the startIndex changes.

Free Resources