'Why there's no Int Index for Set struct in Swift?

I know that Strings in Swift don't have Int indices as Swift supports Grapheme Clusters. But, when coming to Collections in Swift, Array supports Int indices but Set does not support Int indices. What is the reason behind this ?



Solution 1:[1]

Yes, Set has Index (a way to reference, iterate, etc. through members of the collection). But unlike Array, it makes no sense (and offers no utility) for this to be an Int. In an array, a numeric index offers utility for quickly accessing the memory associated for the object at that index. But Set uses hash tables for efficiently identifying items in the collection, not some integer-based offset.

In practice, when using sets, we generally add or remove items from a set and test membership, but we do not generally use indices as they are opaque and generally are not very meaningful or useful for the application developer.

It is a little dense, but the source code for Set is available online. It is complicated a bit because it offers both native “set” implementation, but also bridging to NSSet. But any questions you have ultimately rest in the implementation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1