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.