Get object at index in Set

2019-01-23 12:37发布

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

标签: swift set
2条回答
ゆ 、 Hurt°
2楼-- · 2019-01-23 13:07

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.
查看更多
Ridiculous、
3楼-- · 2019-01-23 13:09

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()
查看更多
登录 后发表回答