Get object at index in Set<T> Get object at index in Set<T> swift swift

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 = 1let 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()


The Type of the index of the Set is not Int. So, you can't retrieve the object using Int subscript, i.e, mySet[2].

You will have to use the index of type Set<String>.Index

let mySet: Set = ["a", "b", "c", "d"]var indices = [Set<String>.Index]()for index in mySet.indices{    indices.append(index)}let thirdIndex = indices[2]print(mySet[thirdIndex]) // prints d (for example)

However, unlike Array, Set is not ordered. Hence, as @Martin pointed out, the object at index 2 is not necessarily "c".