← 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.
Syntax
swift
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

markup
// 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)

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
// 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)
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
  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.