Your Swift screen model has `isLoading`, `articles: [Article]?` and `error: Error?`; when do you replace it with an enum with associated values, and what does that cost?
answer
- count the representable combinations
- payload only where it is valid
- mutating transitions assign self
- no stored properties on enums
- independent flags stay flags
basics
~20 sReplace the flags when the states are mutually exclusive: an enum with payloads makes contradictory combinations unrepresentable. The costs are no stored properties on enums, payload types that must be Equatable for synthesis, and a source break whenever a case is added.
solid answer
~50 sThree independent properties allow eight combinations, and only about four mean anything, so bugs show up as a spinner over an error or a stale error after a successful reload. An enum such as `FeedState` with `idle`, `loading(previous:)`, `loaded([Article])` and `failed(FeedError, previous:)` makes the invalid ones impossible, keeps each payload in the one case where it is valid, and turns transitions into `mutating` methods that assign `self` and can ignore a late response. It costs something: Swift enums cannot have stored properties, so data every phase shares either goes into each payload or into a struct that wraps the enum; synthesized `Equatable` needs every payload to be `Equatable`, which `any Error` is not; and every new case breaks each exhaustive `switch`, which you want inside an app and must plan for in a public library, where Swift 6.2.3 added `@nonexhaustive`. Flags that vary independently, such as `isFavorite`, stay properties.
code
swift · 7 linesstruct Article { let title: String }
struct FeedScreenModel {
var isLoading = false
var articles: [Article]? = nil
var error: Error? = nil
}go deeper
Recall that an enum case can carry data, so a loaded state can hold its articles and a failed state its error.
Explain how mutating methods move the state between cases by assigning self, and how computed properties expose payload data to callers.
Count the representable states of the flag version, show the bugs they allow, and handle shared data with a wrapping struct rather than duplicated payloads.
Decide where the line between exclusive phases and independent flags runs for a team, and whether a public enum commits clients to exhaustive switches or ships as nonexhaustive.
## The problem with flags and optionals A screen model written as a struct of independent properties, `isLoading: Bool`, `articles: [Article]?` and `error: Error?`, can represent 2 × 2 × 2 = 8 combinations of "set or not". A feed screen has about four meaningful phases: idle, loading, loaded and failed. The other combinations are still representable, and real code reaches them: - `isLoading == true` with a non-nil `error`, so the view shows a spinner and an error at once; - a stale `error` left over after a successful reload because one code path forgot to clear it; - `articles == nil` meaning "never loaded" in one place and "failed" in another. Each view and test then has to guess which combination wins. That guessing is the defect an enum removes. ## The enum version With **associated values**, each phase carries exactly the data that is valid in it: - `case idle` carries nothing; - `case loading(previous: [Article])` keeps the old list visible while refreshing; - `case loaded([Article])` carries the result; - `case failed(FeedError, previous: [Article])` carries a typed error and whatever was on screen. Transitions become **`mutating` methods** that assign a new case to `self`, and a method can refuse a transition that makes no sense: `finish(with:)` checks that the state is `loading` and ignores a late response that arrives after the user left. **Computed properties** give views a simple read, such as `var articles: [Article]`, without exposing the matching. Because there is one stored value, every reader sees one phase, and the compiler checks every `switch` over it for completeness. ## What the enum costs in Swift This is a judgment call, not a rule, because the enum has real costs: 1. **No stored properties.** Swift rejects `var lastRefreshed: Date` inside an enum with "enums must not contain stored properties". Data that every phase shares must be repeated in each payload or held by a wrapping struct, `struct FeedScreen { var lastRefreshed: Date?; var phase: FeedState }`. 2. **Reading a payload needs a match.** Callers write `switch` or `if case`, or you add computed properties, which is more API to keep correct. 3. **Equatable is not free.** Synthesized `Equatable` on a payload enum requires every payload type to be `Equatable`; `any Error` is not, so `case failed(Error)` blocks it, and a typed `FeedError` enum fixes it. 4. **Every new case is a source break.** Adding `case empty` makes each exhaustive `switch` in the module stop compiling until it handles the case. Inside an app that is the point: the compiler lists every place to update. ## When to keep properties The enum models **mutually exclusive** phases. Properties that vary independently of the phase, such as `isFavorite`, `isMuted` or a search query, stay properties: folding them into cases multiplies the case count by every combination. The usual shape is a struct for what is always present plus one enum for the phase, which matches costs 1 and 4 above. | Shape | Invalid states | Shared data | Cost of a new phase | |---|---|---|---| | struct of flags and optionals | representable | easy | silent: nothing forces call sites to update | | enum with payloads | unrepresentable | repeated or wrapped | compile errors at every exhaustive `switch` | | struct holding a phase enum | unrepresentable for the phase | in the struct | compile errors, limited to phase handling | ## A public enum in a library The calculation changes when the enum is `public` and other modules switch over it. For a library built with library evolution, a public enum that is not `@frozen` already asks clients to add `@unknown default` to an exhaustive `switch`: a warning in Swift 5 language mode and an error in Swift 6 mode. For other libraries, Swift 6.2.3 added the `@nonexhaustive` attribute (SE-0487), which gives a public enum the same treatment so a new case does not break every client. Committing to exhaustiveness is therefore a versioning decision a library owner makes once and lives with; how clients write `@unknown default` belongs to the lesson on case patterns. ## What interviewers listen for A strong answer counts the representable states, moves each piece of data into the case where it is valid, writes transitions as `mutating` methods, and names the Swift-specific costs: no stored properties, payload `Equatable` requirements and source breaks on new cases, plus the line between exclusive phases and independent flags.
- Where does `lastRefreshed: Date` go once the screen state is an enum?Not inside the enum: Swift enums cannot have stored properties. If every phase needs it, put it in a struct that holds `lastRefreshed` and `phase: FeedState`. If only some phases have it, add it to those payloads, such as `loaded([Article], at: Date)`, so it exists only where it is meaningful.
- Why give the failure case a `FeedError` enum instead of `Error`?`any Error` is not `Equatable`, so synthesized `Equatable` on `FeedState` fails, and comparing states in tests or for change detection gets harder. A small `FeedError` enum is `Equatable` automatically when its payloads are, and it also lists the failures the screen actually renders.
- How do you stop a late network response from overwriting a newer state?Make the transition a `mutating` method that checks the current case first, such as `guard case .loading = self else { return }`, before assigning `.loaded` or `.failed`. A response arriving after the user cancelled or moved on then leaves the state as it is.
A struct of flags is a dashboard of separate warning lights that can all be lit at once; the enum is a gear selector, where engaging one position releases the others, so the car is never in reverse and drive together.
- A Swift enum can hold a stored property shared by every case.
- Enums with associated values can never be Equatable.
- Every boolean on a screen model should become an enum case.
- Adding a case to an app's own enum breaks nothing the compiler can catch.
- A public library enum can gain cases without affecting any client's switch.
Assumes Swift 6.4; the @nonexhaustive attribute for public enums outside library evolution arrived in Swift 6.2.3 (SE-0487), and everything else here holds in Swift 5 and Swift 6 language modes.