Brennan Stehling recently uncovered a fantastic Swift feature I was completely unaware of. I knew you could create raw value enumerations that automatically incremented the value for each case:
enum MyEnumeration: Int { case one = 1, two, three, four } MyEnumeration.three.rawValue // 3
And I knew you could create raw value enumerations with hand-set values:
enum MyEnumeration: Int { case one = 1, three = 3, five = 5 }
But I didn’t know that you could mix and match the two in the same declaration! (Although, you probably shouldn’t do this for standards-based values like the following example…)
enum HTTPStatusCode: Int { // 100 Informational case continue = 100 case switchingProtocols case processing // 200 Success case OK = 200 case created case accepted case nonAuthoritativeInformation } HTTPStatusCode.accepted.rawValue // 202
How cool is that?
I’d probably reserve this approach for values with offsets (for example, “start at 1”), and where the underlying values don’t have established semantics. As Kristina Thai points out, skipping meaningful values doesn’t help readability or inspection.
6 Comments
Hi Erica,
Definitely I nice tip to know, but this functionality has been implemented for quite some time now :]
Swift: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html
> For instance, when integers are used for raw values, the implicit value for each case is one more than the previous case. If the first case doesn’t have a value set, its value is 0.
Java: http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#ordinal%28%29
> Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
C: https://msdn.microsoft.com/en-us/library/whbyts4t.aspx
> By default, the first enumeration-constant is associated with the value 0. The next enumeration-constant in the list is associated with the value of ( constant-expression + 1 ), unless you explicitly associate it with another value.
C#: https://msdn.microsoft.com/en-us/library/sbbt4032(v=VS.100).aspx
> By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
Thanks for sharing your knowledge and findings with the world, though! Wish there were more developers with the determination! :]
Cheers,
Paris
Nice!
What’s a good use case for that though? I don’t think that the HTTP status code is one…
I think the best use case would be the first value as 1, and then contiguous after that, preventing any member from having a raw value of zero so that can be used as a magic value without collisions.
This is cool. There have been cases where I could have used this in past and will in the future.
I like what it can do, but prefer listing out the HTTP codes. I actually thought about this a week or so ago. https://gist.github.com/ollieatkinson/322338df8a5220d649ac01ff11e7de12