Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object at index in Set<T>

Tags:

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

I 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 myObject = mySet[sIndex]; 

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

like image 520
Wim Haanstra Avatar asked Feb 12 '15 06:02

Wim Haanstra


People also ask

How do I get the index of a set in Python?

There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.

Can you index into a set?

As sets are unordered, we can not subscript them with indexes. This does not work like lists.

Does set have index in C++?

A set in c++ is an associative(STL) container used to store unique elements that are stored in a specific sorted order(increasing or decreasing). Elements of the set are unique, i.e., no duplicate values can be stored in the set because each value in the set is a key, and the set doesn't support indexing.


1 Answers

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. 
like image 74
rintaro Avatar answered Sep 20 '22 10:09

rintaro