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:
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
enum Planet: Int {
case mercury = 1, venus, earth, mars
}
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
enum Planet: Int {
case mercury = 1, venus, earth, mars
}
let found = Planet(rawValue: 3)
print(found as Any)
let notFound = Planet(rawValue: 99)
print(notFound as Any)
Login to try C/C++/Java/PHP code in the editor
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: