When porting a UIKit weather screen with loading, error and loaded states to SwiftUI, how does one body replace the view controller's update code?
answer
- stop toggling views by hand
- one enum for the screen's phase
- switch over the phase in body
- shared modifiers on a Group
basics
~20 sModel the screen's state as one enum and switch over it in body, each case describing its whole UI. SwiftUI reads body again when the phase changes and updates the screen, replacing the controller's show, hide and reload calls.
solid answer
~50 sIn the UIKit version the controller creates a spinner, an error label, a retry button and the forecast labels once, and every state change runs code that hides some, shows others and reloads text — miss one line and a spinner lingers over the error. In SwiftUI I model the screen as a `WeatherPhase` enum with `loading`, `failed(message:)` and `loaded(Forecast)` cases, and `body` switches over it so each case declares the complete UI for that state. Apple's documentation describes this as the framework doing most of the work view controllers traditionally do: when the phase changes, SwiftUI reads `body` again and updates the affected parts. Contradictory combinations such as a spinner plus a forecast can't be expressed, and shared modifiers like `navigationTitle` go on a `Group` around the `switch` so they reach whichever case is showing.
code
swift · 42 linesimport SwiftUI
struct Forecast {
let city: String
let celsius: Int
let summary: String
}
enum WeatherPhase {
case loading
case failed(message: String)
case loaded(Forecast)
}
struct WeatherScreen: View {
let phase: WeatherPhase
let retry: () -> Void
var body: some View {
Group {
switch phase {
case .loading:
ProgressView("Loading forecast")
case .failed(let message):
ContentUnavailableView {
Label("No forecast", systemImage: "exclamationmark.triangle")
} description: {
Text(message)
} actions: {
Button("Retry", action: retry)
}
case .loaded(let forecast):
VStack(spacing: 8) {
Text(forecast.city).font(.title)
Text("\(forecast.celsius)°").font(.largeTitle)
Text(forecast.summary)
}
}
}
.navigationTitle("Weather")
}
}go deeper
Recall that a SwiftUI body can switch over an enum and that each case simply lists the views for that state, with no hide or show calls.
Explain why one phase enum beats several flags, how SwiftUI turns a phase change into screen updates, and how Group carries shared modifiers across cases.
Show the port as a review would expect: impossible states removed, no work in body, loading code reduced to assigning a phase, and every state previewable on its own.
Weigh the porting cost of a screen against the bug class it removes, and how a team sequences such ports inside a UIKit app without freezing feature work.
## The imperative version and where it breaks A typical UIKit weather screen creates its subviews once — a spinner, an error label, a retry button, labels for city, temperature and summary — and then a controller method runs on every state change. That method hides some views, shows others, sets text and starts or stops the spinner. Each transition is code someone has to write, and the classic bug is a path that forgets one line: the spinner keeps spinning over the error message, or a stale temperature stays visible after a failed refresh. Apple's documentation frames the SwiftUI alternative directly: as you compose views you declare their data dependencies, and when the data changes SwiftUI updates the affected parts of the interface, so **the framework performs most of the work that view controllers traditionally do**. ## Model the screen's phase as one value The port starts with the data, not the views: ```swift enum WeatherPhase { case loading case failed(message: String) case loaded(Forecast) } ``` - **One value, one truth.** The screen is in exactly one phase at a time. - **Data travels with its case.** The error message exists only in `failed`, the forecast only in `loaded`, so no view can show a forecast that isn't there. - **Impossible combinations disappear.** Separate `isLoading`, `errorMessage` and `forecast` properties allow "loading with an error and an old forecast"; the enum cannot express it. ## Body as a function of the phase `body` then switches over the phase, and **each case describes the complete UI for that state**. The loading case contains a `ProgressView`, the failed case contains a message and a retry button, the loaded case contains the forecast. There is no "hide the spinner" step, because the failed and loaded descriptions simply contain no spinner. When the phase changes, SwiftUI reads `body` again and applies the difference. Because `body` is a view builder, the `switch` produces one conditional type covering all three cases. Wrapping it in `Group` lets modifiers shared by every state — `.navigationTitle("Weather")`, for example — be written once: a modifier on a `Group` applies to its members, so it reaches whichever case is on screen, and `Group` adds no layout of its own. ## What moves where | Concern | Weather view controller | SwiftUI port | |---|---|---| | Creating subviews | Once, then kept and mutated | Described again on each update | | Showing the right state | Hide, show and reload calls | A `switch` in `body` | | Keeping views in sync | Every transition written by hand | SwiftUI updates affected parts | | Shared screen settings | Set on the controller | Modifiers on a `Group` | Some things stay yours. Fetching the forecast and deciding the phase is app logic: where the async call starts belongs to the lesson on appearance and async work, and whether the phase lives in `@State` or an `@Observable` model belongs to the lessons on state and architecture. The view in this question only *reads* a phase, which also makes it trivial to preview in each state. ## Port step by step 1. List every state the controller can be in, including the ones it gets into by accident. 2. Collapse them into an enum whose cases carry the data each state needs. 3. Write one subview or block per case; each must make sense on its own. 4. Switch over the phase in `body`, wrapped in `Group` if the cases share modifiers. 5. Replace the controller's update methods with code that only assigns a new phase. ## Pitfalls in the port - **Porting the flags.** Translating `isLoading` and `errorMessage` one-to-one keeps the contradictory states UIKit allowed. - **Starting work in `body`.** `body` can be read many times; a fetch placed there repeats. - **Imperative habits in modifiers.** Chains of handlers that set flags to show or hide views rebuild the controller inside SwiftUI. - **Erasing to `AnyView` per state.** A `switch` in a builder already handles different view types; erasure is unnecessary here. - **Holding on to a subview to update it later.** SwiftUI views are values; there is no object to keep a reference to, so every update goes through the phase. - **Forgetting the empty result.** A request can succeed with nothing to show for a location; give that its own case or message rather than an empty stack. The interview answer is the contrast in one sentence: instead of writing every transition between states, you describe each state once and let SwiftUI compute the transitions.
- Where does the code that loads the forecast go once the controller is gone?Not in `body`, which SwiftUI may read many times. The view should only read a phase; something else produces it — a model that owns the request, or a modifier that starts async work when the view appears. Those choices are covered with SwiftUI's appearance and async work and its state and architecture lessons; the declarative point is that loading code only assigns a new phase.
- Why does this design make the screen easier to preview and test?Because the view is a function of one input, you can construct it with `.loading`, `.failed(message:)` or `.loaded(...)` directly and see each state without a network call. In the controller version each state was reached by running a sequence of update calls, so showing the error state meant reproducing the path that led to it.
- Porting isLoading and errorMessage flags one-to-one is the natural SwiftUI translation.
- In SwiftUI you still hide the spinner explicitly when loading finishes.
- Fetching the forecast inside body is fine because body runs once.
- Each state needs AnyView because the cases return different view types.
- Modifiers on a Group apply only to the group's first child.