[swift-evolution] Working with enums by name

Brent Royal-Gordon brent at architechies.com
Tue May 31 21:32:50 CDT 2016


> Don't you think it's a bit of a waste to be repeating the name of the value as a string just to use init(rawValue:) with them?

Who said anything about repeating the name?

Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.30). Type :help for assistance.
  1> enum Planet: String { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune }
  2> Planet.mercury.rawValue
$R0: String = "mercury"

> What if I need to store another string associated with the value of the enum e.g. I want to create an enum to represent options in a menu and the associated value is to be the name of the image file to be used for that option?

Use the instance as a key into a dictionary of images. (Or use the rawValue as a key into a plist dictionary of image names. Or just name the image after the rawValue.)

In any case, this sounds like we're back to your other thread, the one about attaching properties to cases. That's a great feature, but it's a different feature from this one.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list