← Back to Swift Course | Chapter 10: Enums | Lesson 2 of 6

Raw Values

A raw value is a plain backup value, like a number or letter, permanently glued to each option in an enum.

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

markup
enum Planet: Int {
    case mercury = 1, venus, earth, mars
}
print(Planet.earth.rawValue)

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

markup
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)
Common Mistakes
  1. Forgetting raw values must all be the same type and, for auto-incrementing Int raw values, unique within the enum.
  2. 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.
  3. 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 String or Int, after a colon.
  • Each case can be given an explicit raw value, or Int cases can auto-increment from 0.
  • EnumName(rawValue:) creates an enum instance from a raw value, returning an optional.
  • .rawValue retrieves a given case's underlying raw value.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.