Get object at index in Set<T>
Swift 3 and newer
You can offsetBy:
from .startIndex
:
let mySet: Set = ["a", "b", "c", "d"]
mySet[mySet.index(mySet.startIndex, offsetBy: 2)] // -> something from the set.
Swift 2 (obsolete)
You can advancedBy()
from .startIndex
:
let mySet: Set = ["a", "b", "c", "d"]
mySet[mySet.startIndex.advancedBy(2)] // -> something from the set.
Swift 1.x (obsolete)
Similar to String
, you have to advance()
from .startIndex
:
let mySet: Set = ["a", "b", "c", "d"]
mySet[advance(mySet.startIndex, 2)] // -> something from the set.
A Set
is unordered, so the object at index is an undefined behavior concept.
In practice, you may build an arbitrary ordered structure out of the Set, then pick an object at index in this ordered structure.
Maybe not optimal, but easy to achieve:
let myIndex = 1
let myObject = Array(mySet)[myIndex]
Note: if you need a random element, starting with Swift 4.2 you get the convenient solution:
let myRandomObject = mySet.randomElement()