Enums with associated and raw values

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does this print?

enum Planet: Int {
    case mercury = 1, venus, earth
}
print(Planet.earth.rawValue)
print(Planet(rawValue: 7) == nil)
Options
Hint 1 of 1

What raw value does venus get?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 3 then true

Correct. earth is 3, and there is no case with raw value 7.

Why not the others?
  • A 2 then false. Raw values start at 1 and count up, so earth is 3.
  • C 3 then false. init(rawValue:) returns nil for unknown values.
  • D It doesn't compile. Implicit raw values for Int enums are allowed.

30-second answer

Raw values give each case a fixed literal of one type (Int, String) and a failable init(rawValue:). Associated values attach different data to each case at runtime, like case success(Data) and case failure(Error). An enum can't have both on the same case, and switches over enums must be exhaustive.

Practise saying it · 30 s. No recording, just a timer

Explain associated vs raw values.

Say your answer out loud, then check which of these points you covered:

  • Raw values are fixed literals
  • Associated values carry data
  • Exhaustive switches

Deep dive

Int raw values auto-increment from the previous case.

CaseIterable gives allCases.

Associated values make invalid states unrepresentable, for example a loading state enum.

indirect allows recursive enums.

Common mistakes

  • Using default: and missing new cases.
  • Modelling exclusive states with several optionals.

Senior take & follow-ups

Seniors use enums to make invalid states impossible.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you add a new case safely?

    Show hint

    Avoid default: so the compiler flags every switch.

  2. What does @unknown default do?

    Show hint

    Warns when a non-frozen enum from another module gains cases.

Suggest a fix if something here is wrong or out of date.