Raw Values
A raw value is a plain backup value, like a number or letter, permanently glued to each option in an enum.
In this page:
Syntax
enum EnumName: Type {
case first = 1, second, third
}
EnumName.first.rawValue
let found = EnumName(rawValue: 2) // EnumName? (optional)
Declaring Raw Values
Adding : Type after the enum name gives every case an underlying raw value of that type, accessible via .rawValue.
Note:
Since
mercury = 1 was set explicitly, Swift auto-increments the rest: venus=2, earth=3, mars=4.Example: Declaring Raw Values
// Define an enum `Planet` listing its possible cases
enum Planet: Int {
// Enum case(s): `mercury = 1, venus, earth, mars`
case mercury = 1, venus, earth, mars
}
// Print `Planet.earth.rawValue` to the console
print(Planet.earth.rawValue)
Login to try C/C++/Java/PHP code in the editor
Creating an Enum from a Raw Value
The failable initializer init?(rawValue:) converts a raw value back into an enum case, returning nil if no case matches.
Example: Creating an Enum from a Raw Value
// Define an enum `Planet` listing its possible cases
enum Planet: Int {
// Enum case(s): `mercury = 1, venus, earth, mars`
case mercury = 1, venus, earth, mars
}
// Declare a constant `found`, set to `Planet(rawValue: 3)`
let found = Planet(rawValue: 3)
// Print `found as Any` to the console
print(found as Any)
// Declare a constant `notFound`, set to `Planet(rawValue: 99)`
let notFound = Planet(rawValue: 99)
// Print `notFound as Any` to the console
print(notFound as Any)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting raw values must all be the same type and, for auto-incrementing
Intraw values, unique within the enum. - Confusing an enum case's raw value with an associated value; a raw value is fixed and shared per case definition, not supplied per instance.
- Trying to initialize from a raw value with
EnumName(rawValue:)and forgetting it returns an optional, since not every raw value maps to a case.
Chapter Summary
- An enum can specify a raw value type, like
StringorInt, after a colon. - Each case can be given an explicit raw value, or
Intcases can auto-increment from 0. EnumName(rawValue:)creates an enum instance from a raw value, returning an optional..rawValueretrieves a given case's underlying raw value.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: