Introduction to SwiftUI
SwiftUI is the modern way to develop iOS, iPadOS, watchOS and macOS applications.
It is a paradigm shift from the “old” way, obsoleting many existing Apple frameworks: UIKit, AppKit and WatchKit.
Those frameworks have one thing in common: they are imperative.
You, the programmer, decide exactly how things should appear, pixel by pixel. You then respond to user events and manually update the data. On each change, you also decide how the UI should change.
SwiftUI is a total change because it’s reactive and the UI reflects the state of the data. No more “connecting things” like in UIKit.
And you write a lot less code. If you’ve ever written a iPhone app using UIKit before, you’ll think “that’s it?” all the time.
Speaking about code, with SwiftUI you just write code. No more StoryBoard or Interface Builder.
I find this perfect because I can store my code in Git and I can immediately see the changes made in time, over some XML gibberish.
Now, if you never worked with UIKit before, you’ll not understand what I mean. That’s good for you, don’t worry.
Since Apple was able to work on a clean slate with SwiftUI, we have so many advantages.
A first encounter with a SwiftUI app is fascinating.
This is the code of an Hello World app:
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello World")
}
}
You import the SwiftUI module, and you declare a struct
that conforms to the View
protocol.
This protocol requires that the struct has a computed property called body
that returns some View
.
And that’s what we do inside the struct.
The body
computed property returns a single view of type Text
, with the content Hello World
in it.
Since you’ll see some View
used all the time in SwiftUI, it’s a good time to explain why we use that and not just View
.
This declaration forces body
to always return a view of the same type, something that’s essential for how SwiftUI works.
One reason if performance. In order to be performant, SwiftUI needs to give some things for granted. One of those is that every struct returns the same kind of view, so it can easily check if it needs to be redrawn on screen, or not.
In this case we return a Text
view, and this is what our struct will always return, regardless of its state.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025