String raw values
Similar to the handy trick of incrementing an Int raw value, if you specify a raw value type of String you’ll get another automatic conversion. Let’s pretend you’re
building a news app that has tabs for each section. Each section has an icon. Icons are a good chance to deploy enumerations because by their nature, they are a limited set:
// 1
enum Icon: String { case music
case sports case weather
var filename: String {
// 2
return "(rawValue.capitalized).png"
}
}
let icon = Icon.weather icon.filename // Weather.png
Here’s what’s happening in this code:
- The enumeration sports a String raw value type.
- Calling rawValue inside the enumeration definition is equivalent to calling self.rawValue. Since the raw value is a string, you can request the capitalized version which will give you an uppercase first letter.
Note you didn’t have to specify a String for each member value. If you set the raw value type of the enumeration to String and don’t specify any raw values yourself, the compiler will use the enumeration case names as raw values. The filename computed property will generate an image asset name for you. You can now fetch and display images for the tab icons in your app.
Next, let’s jump back to working with number raw values and learn how to use enumerations for banking.