Get object at index in Set

2019-01-23 12:34发布

问题:

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'?

回答1:

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.

Swift 3

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


回答2:

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()


标签: swift set