0

Accessing Set elements is fast, and Set type must to be hashable.

I thought so Swift store only hashed-value of each element, but I fount the raw value (not hashed) could also be accessed. e.g like this:

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

for genre in favoriteGenres {
    print("\(genre)")
}

Output:

// Jazz
// Hip hop
// Classical

How does swift store Set type in memory And access it?

rick
  • 1,009
  • 2
  • 10
  • 28
  • 2
    If you are interested in the actual implementation: Swift is open source and [HashedCollections.swift.gyb](https://github.com/apple/swift/blob/master/stdlib/public/core/HashedCollections.swift.gyb) is well documented :) – Martin R Mar 03 '18 at 10:13

1 Answers1

0

Your are right, Swift stores the hashed value.

All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and can be used as set value types or dictionary key types. Enumeration case values without associated values (as described in Enumerations) are also hashable by default.

If you store your own custom types they must be conform to the Hashable protocol.

You can use your own custom types as set value types or dictionary key types by making them conform to the Hashable protocol from Swift’s standard library. Types that conform to the Hashable protocol must provide a gettable Int property called hashValue.[...]

See https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html -> Sets

In the documentation I can't found the exactly way how they store Set Types but as I understand the Sets they access about the hashed values.

kuzdu
  • 7,124
  • 1
  • 51
  • 69