SwiftUI Fundamentals
SwiftUI replaces the imperative habit of UIKit, where you build a view hierarchy and then mutate it, with a declarative one: you describe what the screen should look like right now, and the framework works out how to get there. That sounds like a small change in syntax, but it moves where your code lives. A UIKit view controller owns objects and has to be told when to update them. A SwiftUI view is a cheap value type that gets thrown away and rebuilt, and the thing that decides what it looks like is a small piece of state. Before that idea is useful you need the machinery underneath it, and that is what this page covers: how an app starts, what a view actually is, how views are arranged, how they are modified, and how you look at what you have built without leaving the editor.
Everything here is written for Swift 5.9 and iOS 17 or later. Where a newer API replaced an older one, both are shown, because most code you will read in the wild still uses the older form.
In UIKit you are the imperative narrator of a story. You create a label, add it to a stack view, and later, when a value changes, you reach into the label and assign to its text property. The order in which you write those lines is part of the meaning of the program.
In SwiftUI you write the description of the story’s current frame. A view is a value that returns another view. When the state it depends on changes, SwiftUI discards the old description, evaluates a new one, and diffs the result against what is on screen to work out the smallest set of changes to apply.
| Concern | UIKit | SwiftUI |
|---|---|---|
| Who owns the screen | A view controller instance | A value type created by the framework |
| How updates happen | You assign to properties | State changes, framework re-evaluates |
| How layout happens | You ask for a layout pass | You describe constraints, framework sizes it |
| How a control reports a change | Target and action, or a closure | A closure, usually a method reference |
| How a screen is assembled | Code in viewDidLoad | A value returned from body |
The practical consequence is that the majority of a UIKit screen is bookkeeping. The majority of a SwiftUI screen is description. That shift is why SwiftUI code tends to be shorter, and also why the rules about where state lives become the central discipline, which is the subject of the next chapter.
A SwiftUI app starts with a single type that conforms to the App protocol and is marked with the @main attribute.
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Three pieces matter here.
@main is an entry point attribute, the Swift equivalent of UIApplicationMain. The compiler synthesises the call to UIApplicationMain for you, so there is no AppDelegate.swift and no main.swift unless you ask for one.
App is the protocol that replaces UIApplicationDelegate for most purposes. It has exactly one requirement, body, and body returns a Scene rather than a View. A scene is the unit of multitasking: the system gives a scene a window, a place in the app switcher, and a lifecycle.
Scene is what the app actually shows. WindowGroup is the usual one, and it describes a window whose content is the closure you give it. Other options are Window for a single-window application, Settings for a preferences scene on macOS, and MenuBarExtra for a menu bar item.
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
// A second scene type is allowed; each WindowGroup becomes
// its own window when the system asks for one.
Settings {
SettingsView()
}
}
}
Inside the WindowGroup closure you place a View. That is the whole app: a scene containing a view, and a view is a function that returns a view.
A fresh Xcode project with the SwiftUI App lifecycle selected contains very little code, which is part of the point.
MyApp/
├── MyApp.xcodeproj
├── MyApp/
│ ├── MyAppApp.swift the @main type and its WindowGroup
│ ├── ContentView.swift the root view of the window
│ ├── Assets.xcassets app icon, colours, images
│ └── Preview Content/ assets used only by previews
└── MyAppTests/
Four of these deserve comment.
The app entry file holds the @main type. It exists so that the window structure is in one obvious place and so that a project can add scenes later without hunting through view code.
The asset catalogue is where the app icon, named colours and any bundled images live. SwiftUI prefers named assets over loose files because the catalogue can hold multiple appearances of the same name, one per colour scheme or device idiom, and Xcode will pick the right one at runtime.
The preview content group holds assets that are only used by the preview canvas. It is excluded from the shipped app, so you can keep a large placeholder image in it without inflating the bundle.
Preview Content also exists as a legacy convention. In older Xcode templates the preview canvas rendered a placeholder unless you supplied a Preview Content folder, and the asset named Preview Content at the root of the catalogue was what the template looked for. Current Xcode versions do not require it, and a template with the SwiftUI lifecycle selected usually does not create the folder at all.
One more thing Xcode does for you is the Info.plist. Newer projects use generated Info plists: you set a key in the target settings, Xcode writes the corresponding key into the built bundle, and there is no file to merge. If you open the target settings and look for “Info”, you will find entries like INFOPLIST_KEY_UILaunchScreen_Generation, which is how the launch screen is declared now.
A SwiftUI view is any type that conforms to View. The protocol has one requirement, body, plus a large set of default implementations that supply the many convenience methods you call as modifiers.
struct Greeting: View {
let name: String
var body: some View {
Text("Hello, \(name)")
}
}
The some View return type is worth understanding, because it is the source of a whole family of confusing errors.
View cannot simply be a concrete return type, because the return type of body is frequently a different type for every view you write. Greeting.body returns Text, ContentView.body might return VStack, and a view built from a ForEach might return some other wrapper. If body had to return View, then the compiler would have to erase the concrete type into the View existential, which is expensive and would throw away type information that SwiftUI itself needs.
some View solves this by declaring an opaque return type. The compiler knows the exact concrete type, keeps it for the optimiser, and hides the name from the caller. The rule that matters in practice is that the opaque type must be the same on every code path, and that you cannot put a protocol with associated types or a composition of several different types behind a single some without erasing them first.
This is why you will eventually meet the error “function opaque return type inferred some View does not conform to View”. It means that somewhere in the body you returned two unrelated types. The fix is to wrap them in a container such as VStack, Group, or TupleView.
The other half of the story is @ViewBuilder. Most SwiftUI containers build their content with a result builder, which means you can write several views in a row without commas, and the builder decides how to combine them.
var body: some View {
VStack {
Text("Title") // no commas, no array
Text("Subtitle")
}
}
VStack accepts up to ten children directly. The eleventh is a compile error, and the usual fix is a Group or a ForEach rather than a clever nesting scheme.
SwiftUI ships a small number of primitives and a large number of ways to compose them. These four cover most of a first screen.
Text displays a string. It has a static initialiser for literal strings and a LocalizedStringKey initialiser for anything that should be localised, which is why Text("Hello") is automatically looked up in a strings table.
Text("Hello, world!")
Text("Count: \(count)")
Text(verbatim: "100% literal") // no localisation lookup
Image displays an image. It takes a resource from the asset catalogue by name, a system symbol by name, or raw image data.
Image("hero-photo")
.resizable()
.scaledToFill()
Image(systemName: "star.fill")
.foregroundStyle(.yellow)
Button runs an action. Modern SwiftUI prefers the trailing-closure form and, where a method matches the signature, a plain method reference.
Button("Save") {
save()
}
Button("Save", action: save)
Button {
save()
} label: {
Label("Save", systemImage: "square.and.arrow.down")
}
TextField collects text. It comes in three flavours, and picking the wrong one is a common source of trouble with the keyboard.
TextField("Name", text: $name) // plain text
TextField("Amount", value: $amount, format: .number) // typed value, numeric keyboard
SecureField("Password", text: $password) // masked entry
The dollar sign in $name is not part of the variable name. It is a projected value: SwiftUI projects a String property into a Binding<String>, which is a two-way connection to the storage that holds it. The chapter on state management picks this up in detail.
Layout in SwiftUI is done with containers, not with constraints. You nest them.
VStack { // vertical
Text("Header")
Text("Body")
}
HStack { // horizontal
Image(systemName: "person.crop.circle")
Text("Profile")
}
ZStack { // overlapping
Color.black.opacity(0.4)
Text("Overlay")
}
Spacer() // flexible empty space
Divider() // a hairline rule
VStack and HStack size themselves to fit their children, and they distribute along their axis. Spacer is the tool for pushing things apart: it expands to fill the available space, so a Spacer() inside an HStack sends the first child to the leading edge and the second to the trailing edge.
The modifiers that decide how a stack behaves relative to its container are alignment and spacing.
VStack(alignment: .leading, spacing: 12) {
Text("Left aligned")
Text("Second row")
}
.frame(maxWidth: .infinity, alignment: .leading)
The frame modifier deserves special attention because it is where sizing decisions usually go wrong. frame(width:height:) proposes a fixed size, frame(minWidth:maxWidth:) proposes a range, and .frame(maxWidth: .infinity) means “take all the space offered, up to infinity”. A view that takes all the horizontal space becomes greedy, and greedy children push the others out. This is why a header row usually reads .frame(maxWidth: .infinity, alignment: .leading) rather than just .padding().
A modifier is a method on View that returns a new view wrapping the original. Because each one returns another view, they chain.
Text("Title")
.font(.title)
.fontWeight(.bold)
.foregroundStyle(.primary)
.padding()
.background(Color.gray.opacity(0.2))
.clipShape(RoundedRectangle(cornerRadius: 8))
Order is not cosmetic. A modifier changes the view it receives and hands the result to the next one, so the chain reads from the inside out.
Text("Hello")
.padding()
.background(Color.red) // background of the padded area
Text("Hello")
.background(Color.red)
.padding() // red block, then space around it
The second version paints the background before padding is added, so the red covers only the glyphs and the padding sits outside it. If you find a view that looks wrong in a way that does not match the code, check the order before anything else.
You can also write your own modifier by conforming to ViewModifier and adding a View extension that returns the modified view.
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding(16)
.background(Color(.secondarySystemGroupedBackground))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
extension View {
func cardStyle() -> some View {
modifier(CardStyle())
}
}
Content is a type-erased placeholder for the view being modified, and it is what lets one modifier work with any view. The modifier is applied with .cardStyle().
SF Symbols is a system icon library with thousands of symbols, shipped with the operating system and free to use. It is the reason a modern SwiftUI app rarely needs a designer for simple icons.
Image(systemName: "star.fill")
.imageScale(.large)
.foregroundStyle(.yellow)
Symbols are vector images, so they scale without blurring and they follow the current accent colour and text style. Three modifiers control their appearance.
Image(systemName: "wifi")
.symbolRenderingMode(.hierarchical) // draws the symbol in one tone
.symbolVariant(.fill) // the filled variant of the symbol
.foregroundStyle(.secondary)
A symbol name that does not exist renders as an empty box, which is a silent failure. If an icon looks blank, check the name in the SF Symbols app that ships with Xcode, or open the SF Symbols catalogue in Xcode’s asset editor.
For images that come from the network, AsyncImage handles the loading, the placeholder and the failure case.
AsyncImage(url: avatarURL) { phase in
switch phase {
case .success(let image):
image.resizable().scaledToFill()
case .failure:
Image(systemName: "person.crop.circle.badge.exclamationmark")
case .empty:
ProgressView()
@unknown default:
ProgressView()
}
}
The preview canvas is the single most useful tool in Xcode for SwiftUI, because it renders a view without launching the app, in a fake device frame, with sample data, and it refreshes as you type.
Xcode 15 and later use the #Preview macro.
#Preview("Greeting") {
Greeting(name: "Ada")
}
#Preview("Compact width") {
Greeting(name: "Ada")
.frame(width: 200)
}
Previews get sample data from the preview attributes of the surrounding type, so you can write several previews of the same view with different inputs.
struct Greeting: View {
let name: String
var body: some View {
Text("Hello, \(name)")
}
#Preview("Short name") {
Greeting(name: "Bo")
}
#Preview("Full name") {
Greeting(name: "Bo Jensen")
}
}
The canvas can also be told how to present the preview: a display name, a device, a layout, an orientation.
#Preview("iPad") {
Greeting(name: "Ada")
.previewDisplayName("Greeting on iPad")
.previewDevice("iPad Pro 11-inch")
.previewLayout(.sizeThatFits)
}
The older PreviewProvider protocol still works and you will meet it in existing code.
struct Greeting_Previews: PreviewProvider {
static var previews: some View {
Greeting(name: "Ada")
}
}
The canvas has three controls worth knowing. Resume restarts the preview after you change global state such as an environment value. Select an element highlights a view in the hierarchy so you can see which one is which. And the console next to the canvas shows anything you printed, which is often the quickest way to understand what your body actually evaluated to.
App replaced UIApplicationDelegate for most day-to-day work, but UIKit still exists underneath and some capabilities still require it.
The scene phase tells you whether the app is in the foreground, inactive or in the background. It is the modern replacement for the old applicationDidBecomeActive style callbacks.
struct ContentView: View {
@Environment(\.scenePhase) private var scenePhase
var body: some View {
Text("Running")
.onChange(of: scenePhase) { _, newPhase in
if newPhase == .background {
saveProgress()
}
}
}
}
If you genuinely need a UIApplicationDelegate, for example to handle a push registration or a remote notification, you adopt it through UIApplicationDelegateAdaptor rather than by replacing your App type.
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
// Forward the token to your backend.
}
}
UIKit views can be dropped into a SwiftUI hierarchy with UIViewControllerRepresentable, and SwiftUI views can be embedded in UIKit with UIHostingController. You will not need either while learning the basics, but knowing they exist removes the fear of a dead end.
So far everything is static. To make a view react to something, you mark the storage that holds the changing value with @State.
struct Counter: View {
@State private var count = 0
var body: some View {
VStack(spacing: 12) {
Text("Tapped \(count) times")
.font(.title2)
Button("Increment") {
count += 1
}
}
}
}
@State tells SwiftUI two things: this view owns the value, and the view must be redrawn when the value changes. The value itself is not stored in the view, because views are values and get recreated. The state lives outside the view, in storage SwiftUI manages, and the view holds a pointer to it.
Three rules cover most of what you need to know for now. A value marked @State should be private. It should be initialised at the declaration site, because the initialiser runs every time the view is recreated, and it should hold a value type such as String, Int, Bool, an array, or a struct. Reference types are covered in the next chapter.
| Mistake | What happens | Correction |
|---|---|---|
Returning different types from body | “Opaque return type inferred some View does not conform to View” | Wrap the branches in a VStack or a Group |
Forgetting @State on a value you change | The change does nothing, or a warning about a constant | Mark the property @State |
Putting a frame before the padding it should surround | Padding ends up outside the background | Move the modifiers into the intended order |
Greedy frames in a VStack | Children are pushed off screen or clipped | Constrain the frame to the axis you care about |
| A symbol name that does not exist | A blank square, no error | Check the name in the SF Symbols catalogue |
Expecting body to run once | It runs again on every state change | Keep body cheap; move work into methods or tasks |
| Overriding the launch storyboard by hand | A black screen on launch | Use the generated launch screen setting |
Build a ProfileCard view in a fresh SwiftUI project. It should show a circular avatar image built from an SF Symbol, a name, a short subtitle, and a rounded rectangle background. Put a Spacer between the avatar and the text so the text aligns to the leading edge. Add a Button whose label uses Label with a system image. Give the whole card a custom ViewModifier called elevatedCard that applies padding, a background, and a corner radius. Finally, add a @State boolean named isExpanded and a button that toggles it, showing the subtitle only when it is true.
When you are done, add a #Preview that shows the card in both states, and run the app on the simulator to check that the live canvas matches what you expected.
Approach:
The exercise is a tour of the building blocks in the order they stack: a custom View struct, the primitive views it contains, the container that arranges them, the modifier chain that styles the result, and finally the state that makes it interactive. Writing it in that order keeps every step independently checkable, because each one can be previewed before the next is added. The trap is the custom modifier: it must wrap the content rather than replace it, which is what the Content placeholder in ViewModifier is for.
Steps:
- Create
ProfileCardconforming toView, withlet name: String,let subtitle: Stringand@State private var isExpanded = false. The two strings are inputs and must not be state; the boolean is owned by the view and must be. - Put the content in an
HStackwith aSpacer()between the avatar and the text column, so the text is pushed to the leading edge and the row fills the width. - Build the avatar as
Image(systemName: "person.crop.circle.fill")with.resizable()and.frame(width: 48, height: 48)so it is a fixed size rather than a greedy one. - Build the text column as a
VStack(alignment: .leading)containing the name, and the subtitle inside aGroupthat is only rendered whenisExpandedistrue. Guarding with aGroupkeeps the two branches the same type. - Give the button a
Labellabel with achevron.downorchevron.upsymbol, and toggleisExpandedin the action. - Write the
elevatedCardmodifier as aViewModifierwhosebody(content:)applies.padding(16), a background usingColor(.secondarySystemBackground), and.clipShape(RoundedRectangle(cornerRadius: 12)). Apply it with.elevatedCard()after the background it is meant to cover. - Add two
#Previewblocks, one withisExpandedset totruethrough the initialiser or by a small wrapper view, and one with itfalse, and use.previewLayout(.sizeThatFits)so the card is not stretched to the full canvas.
Answer:
A correct implementation looks like this.
struct ProfileCard: View {
let name: String
let subtitle: String
@State private var isExpanded = false
var body: some View {
HStack(spacing: 12) {
Image(systemName: "person.crop.circle.fill")
.resizable()
.frame(width: 48, height: 48)
Spacer()
VStack(alignment: .leading, spacing: 4) {
Text(name)
.font(.headline)
Group {
if isExpanded {
Text(subtitle)
.font(.subheadline)
.foregroundStyle(.secondary)
}
}
Button {
isExpanded.toggle()
} label: {
Label(
isExpanded ? "Show less" : "Show more",
systemImage: isExpanded ? "chevron.up" : "chevron.down"
)
}
.font(.caption)
}
}
.elevatedCard()
}
}
struct ElevatedCardModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding(16)
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
extension View {
func elevatedCard() -> some View {
modifier(ElevatedCardModifier())
}
}
#Preview {
ProfileCard(name: "Ada Lovelace", subtitle: "Analyst and writer")
.padding()
.previewLayout(.sizeThatFits)
}
#Preview("Expanded") {
ProfileCard(name: "Ada Lovelace", subtitle: "Analyst and writer")
.padding()
.previewLayout(.sizeThatFits)
}The behaviours to verify are that the card renders with a background and rounded corners, that the subtitle appears only after the button is tapped, that the button label swaps between the two symbols, and that the two previews agree with the running app. If the background covers the wrong area, the modifier is applied in the wrong position in the chain; if the subtitle always shows, the Group wrapper has been dropped and the two branches are no longer the same type.
