Friday, December 2, 2016 [Tweets] [Favorites]

The RawRepresentable Protocol in Swift

Ole Begemann:

Note that adding raw values to an enum doesn’t affect how the enum is laid out in memory. The compiler always determines how many bits it needs to discriminate between all enum cases and then assigns a unique integer tag value to each case. Even for enums with integer raw values, this tag is not the same as the raw value — they are completely different things. This also means you don’t have to worry that an enum with strings as raw values will take up more memory than a “plain” enum — the constant strings are only stored once in the binary, not for each instance.

[…]

In fact, the raw value syntax is simply shorthand for conforming the enum to the RawRepresentable protocol, which defines the rawValue property and initializer. When you define the above enum, the compiler generates code equivalent to this[…]

[…]

Once you realize that there’s no magic behind enums with raw values, it opens up the possibility to use all kinds of types as raw values.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment