UIKit and SwiftUI
TrailLog's team hears that a new screen could be written in SwiftUI in a third of the code. But the app is UIKit today. Do they rewrite everything? No — the two frameworks think differently, and they also work together.
The rule
UIKit: you change the views. SwiftUI: you change the state, and views follow.
UIKit is imperative. You create view objects, keep references to them, and tell them what to change whenever data changes:
// UIKit: every change is an instruction
func hikeCountChanged() {
countLabel.text = "\(hikes.count) hikes"
emptyStateView.isHidden = !hikes.isEmpty
}Forget one of those lines and the screen shows something the data does not. Keeping views in sync with data is your job.
SwiftUI is declarative. You describe what the screen should look like for any given state. When the state changes, SwiftUI works out what to redraw:
// SwiftUI: describe the result
struct HikeCountView: View {
let hikes: [Hike]
var body: some View {
if hikes.isEmpty {
Text("No hikes yet")
} else {
Text("\(hikes.count) hikes")
}
}
}There is no label reference and no "update" function. The view is a function of its data.
How they compare in practice:
- UIKit (since 2008) — mature, very detailed control, huge amount of existing code; more code for simple screens.
- SwiftUI (since 2019, iOS 13) — less code, live previews, state-driven; some advanced behaviours still need UIKit.
They interoperate both ways:
UIHostingControllerputs a SwiftUI view inside a UIKit app.UIViewRepresentableandUIViewControllerRepresentablewrap UIKit views inside SwiftUI.
So TrailLog can build its next screen in SwiftUI and push it from an existing UIKit screen with UIHostingController(rootView: StatsView()). The rest of this course's platform knowledge — lifecycle, threads, memory, Xcode — applies to both.
The shortcut
To tell which style you are reading, look for mutation of views. Lines like label.text = or view.isHidden = are imperative UIKit. A body that returns views built from data is declarative SwiftUI.
Decide the style
A simple, data-driven screen: total distance, longest hike. Declarative SwiftUI suits it.
The trap is thinking one must replace the other in a single rewrite. Most real apps migrate screen by screen.
Drills
Answer fast — trust the rule.
Which line is imperative UIKit style?
How do you show a SwiftUI view inside a UIKit app?
In SwiftUI, what makes the screen update when the hike list changes?
TrailLog is a large UIKit app. What is the usual way to adopt SwiftUI?
Remember
- UIKit: you change the views. SwiftUI: you change the state, and views follow.
- Spot the style by looking for view mutation versus a
bodybuilt from data. - They interoperate:
UIHostingControllerone way,UIViewRepresentablethe other.
