skip to content

In Swift, why does a switch over an SDK enum such as URLSessionTask.State need @unknown default, and how does Swift 6 language mode change the diagnostic?

level: seniorimportance: should knowfreq 50%

answer

  1. frozen versus nonfrozen enums
  2. cases added after you ship
  3. matches anything, still warns
  4. warning in Swift 5 mode
  5. error in Swift 6 mode

basics

~20 s

A nonfrozen enum (from C or Objective-C, the standard library or a library-evolution module) can gain cases after you ship. @unknown default handles those yet still flags skipped known cases; omitting it warns in Swift 5 mode, errors in Swift 6 mode.

solid answer

~50 s

For an enum compiled into your own module, listing every case makes a switch exhaustive, and adding a case breaks every such switch, which is the point. A **nonfrozen** enum, such as an Objective-C `NS_ENUM` like `URLSessionTask.State`, a standard-library or overlay enum, or an enum from a module built with library evolution, may gain cases after you ship. Listing the known cases is then not enough: Swift 5 mode warns `switch covers known cases, but 'URLSessionTask.State' may have additional unknown values, possibly added in future versions`, adding that this is an error in the Swift 6 language mode, and Swift 6 mode makes it one. `@unknown default` matches any value like `default`, but the compiler still warns `switch must be exhaustive` if a known case is missing, so you keep the prompt that a plain `default` silences. It must be the last case and cannot take a `where` clause.

code

swift · 16 lines
swift
import Foundation

func label(for state: URLSessionTask.State) -> String {
    switch state {
    case .running:
        return "running"
    case .suspended:
        return "paused"
    case .canceling, .completed:
        return "finished"
    @unknown default:
        return "unrecognised state"
    }
}

print(label(for: .running))

go deeper

for a junior

Recall that many enums from Apple's SDKs and Objective-C headers can gain cases later, and that a switch over them ends with @unknown default.

for a middle

Explain frozen versus nonfrozen, that @unknown default matches any value but keeps the missing-case warning, and that Swift 6 mode turns the omission into an error.

for a senior

Show the migration judgment: clear these warnings while still in Swift 5 mode, keep @unknown default bodies simple because they cannot be tested, and never trade them for plain default.

for a principal

Weigh exhaustiveness as an API promise: an SDK enum you consume can grow, and a package's public enum either commits to its cases or reserves growth, which costs every client a catch-all.

## Frozen and nonfrozen enums Swift's promise that a `switch` is **exhaustive** works perfectly when the compiler sees every case of the enum and nobody can add one without recompiling your code. For an enum declared in your own module, that is true: list every case and no `default` is needed, and when someone adds a case, every exhaustive `switch` over it stops compiling. That breakage is the feature — the compiler walks you to every place the new case must be handled. A plain `default` throws that away, because it quietly absorbs the new case. Some enums cannot make that promise. A **nonfrozen enumeration** may gain new cases **after your app is compiled and shipped**. The book lists where they come from: code compiled in **library evolution** mode, the Swift standard library, the Swift overlays for Apple frameworks, and C and Objective-C code. SE-0192 adds that an `NS_ENUM` with no extensibility annotation is imported as nonfrozen, and `URLSessionTask.State` is one: a future OS can return a state that did not exist when your binary was built. An enum the library author promises will never change is marked `@frozen`; `Optional` is the standard example. ## What the compiler says, by language mode The rule changed with the Swift 6 language mode. The compiler's feature list names it `NonfrozenEnumExhaustivity`, an upcoming feature that Swift 6 mode turns on. | Switch over a nonfrozen enum | Swift 5 mode | Swift 6 mode | |---|---|---| | Every known case, no catch-all | Warning: `switch covers known cases, but 'URLSessionTask.State' may have additional unknown values, possibly added in future versions; this is an error in the Swift 6 language mode` | Error, same text without the suffix | | Known cases plus `@unknown default`, one known case missing | Warning: `switch must be exhaustive`, note `add missing case` | Same warning | | A few cases plus plain `default` | Silent | Silent | SE-0192, the proposal that introduced `@unknown`, also says what happens in Swift 5 mode if you ignore the warning: a program **traps at run time** if an unknown case is actually encountered. ## Why `@unknown default` and not `default` - Both match **any** value. SE-0192 is explicit that `@unknown default` is a catch-all, not a "future cases only" filter. - The difference is at compile time: with `@unknown default`, the compiler still checks that every **known** case is handled and warns when one is not. When an SDK update adds a case, your next build warns at exactly this switch. - A plain `default` handles unknown values safely too, but it also swallows known cases you forgot, now and in every future SDK, with no diagnostic. - It is a warning rather than an error so that adding a case to a library stays source compatible for its clients. ## Rules for `@unknown` 1. It may only mark a catch-all: `@unknown default:` or the equivalent spelling `@unknown case _:`. 2. It must be the **last** case in the switch. 3. It cannot carry a `where` clause; for `@unknown case _ where …` Swift reports `'where' cannot be used with '@unknown'`, and `@unknown default where …` is rejected because `default` never takes a `where`. 4. It cannot be combined with other patterns in a compound case. 5. Its body cannot be exercised by a test, because no code can construct an enum value outside its known cases. Keep the body simple — log, fall back to a safe state — and make it obvious in review. ## Your own enums, and packages `@unknown default` is also accepted over an enum declared in your own module, and the missing-case warning still applies there, so it can serve as a fallback that still nags. Usually, though, an exhaustive switch with no catch-all is better for your own enums: the build already breaks when a case is added. Library authors who do not build with library evolution got a way to reserve the right to add cases in **Swift 6.2.3**: SE-0487's `@nonexhaustive` attribute makes clients in other modules handle unknown values as though the enum were nonfrozen, while code in the same module or package still switches exhaustively. The proposal lists adding `@nonexhaustive` to an existing public enum in such a module as an API-breaking change. ## In practice - Every switch over an SDK or C enum gets `@unknown default`, even when it lists every known case. - Keep the warning visible: a `switch must be exhaustive` warning after an SDK upgrade is a to-do item, not noise to suppress. - Migrating a target to Swift 6 mode turns every missed one into a build error, so fix them while still in Swift 5 mode, where they are warnings.

  • What happens at run time if a Swift 5 mode switch over a nonfrozen enum has no catch-all and an unknown value arrives?
    Swift 5 mode lets that switch compile with only a warning, and SE-0192, the proposal that introduced `@unknown`, says the program traps if an unknown case is actually encountered. A catch-all turns that into a branch you control, which is why Swift 6 mode makes it mandatory.
  • Can you write @unknown default in a switch over an enum declared in your own Swift module?
    Yes. Swift 6.4 accepts it without complaint when every case is listed, and still warns `switch must be exhaustive` when one is missing. That gives a fallback branch that keeps the per-case prompt, although for your own enums a plain exhaustive switch is usually enough, since a new case already breaks the build.
  • How can a Swift package that does not use library evolution reserve the right to add cases to a public enum?
    Swift 6.2.3 implemented SE-0487's `@nonexhaustive` attribute. Clients in other modules must then handle unknown values as if the enum were nonfrozen, while code in the same module or package can still switch exhaustively. The proposal lists adding the attribute to an existing public enum as an API-breaking change for such modules.

A plain default is an 'other' box on a form that silently takes anything, including options you forgot to list; @unknown default is the same 'other' box with a clerk who still complains whenever a printed option is missing.

  • Listing every known case makes any switch exhaustive, SDK enums included.
  • @unknown default only runs for cases added after the code was compiled.
  • A plain default and @unknown default produce exactly the same diagnostics.
  • Missing @unknown default is a warning in every Swift language mode.
  • @unknown default can take a where clause like any other case.

Assumes Swift 6.4: omitting a catch-all over a nonfrozen enum warns in Swift 5 language mode and is an error in Swift 6 mode; @nonexhaustive for non-resilient packages arrived in Swift 6.2.3 (SE-0487).