Wim Haanstra Wim Haanstra - 1 month ago 7
Swift Question

Get object at index in Set<T>

In Swift 1.2 there is a Set object, which you can use to create a static typed Set.

I only cannot find out how to get the object at a certain index. It has a

subscript
that allows you to do the following:
mySet[setIndex]
.

This retrieves the object at that
setIndex
. But now I want to get an object from a certain
Int
index.

var sIndex = mySet.startIndex;
var myObject = mySet[sIndex];


But how do I create a SetIndex with a certain 'index'?

Answer

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.

ADDED: As of Xcode7 beta6/Swift2.0:

let mySet: Set = ["a", "b", "c", "d"]
mySet[mySet.startIndex.advancedBy(2)] // -> something from the set.
Comments