๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Raw Value Lookup

A raw value lookup builds an enum value from a raw value. The lookup gives a matching case for a known raw value and nil for an unknown one.

A lookup that finds its case

The raw value 3 belongs to the earth case of Planet. The if let block prints the found case and its raw value.

enum Planet: Int {
    case mercury = 1
    case venus
    case earth
    case mars
}
if let planet = Planet(rawValue: 3) {
    print(planet)
    print(planet.rawValue)
}

A lookup that finds nothing

No Planet case owns the raw value 9. The else block runs because the lookup gives nil.

enum Planet: Int {
    case mercury = 1
    case venus
    case earth
    case mars
}
if let planet = Planet(rawValue: 9) {
    print(planet)
} else {
    print("No such planet")
}

A fallback with ??

The lookup for 9 gives nil, so the ?? operator supplies the mercury case. The prints show that fallback case and its raw value.

enum Planet: Int {
    case mercury = 1
    case venus
    case earth
    case mars
}
let planet = Planet(rawValue: 9) ?? Planet.mercury
print(planet)
print(planet.rawValue)

Looking up cases from text

Each stored word goes through a Medal lookup. The word plastic matches no case, so its pass prints the unknown line.

enum Medal: String {
    case gold
    case silver
    case bronze
}
let inputs = ["gold", "plastic", "bronze"]
for text in inputs {
    if let medal = Medal(rawValue: text) {
        print(medal.rawValue)
    } else {
        print("unknown")
    }
}

Example

enum Level: Int {
    case low = 1
    case middle
    case high
}
if let level = Level(rawValue: 2) {
    print(level)
}
let backup = Level(rawValue: 8) ?? Level.low
print(backup)

Key points

  • Writing the type name with (rawValue:) tries to build a case from the given raw value.
  • The result of a lookup is an optional because the lookup can fail.
  • A known raw value gives the case that owns that raw value.
  • An unknown raw value gives nil.
  • if let runs its block only when the lookup gives a case.
  • The ?? operator supplies a fallback case when the lookup gives nil.

In this example, the Level enum counts its raw values from 1, so the raw value 2 belongs to the middle case. The if let block prints middle. The second lookup asks for 8, gets nil, and the ?? operator supplies the low case, so the last print shows low.

Note

A String raw value lookup must match the raw text exactly, including letter case.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Planet(rawValue: 9) give when no Planet case owns the raw value 9?