The Complete SwiftUI Guide
By Flavio
Published · Updated
Tagged: Swift
Learn SwiftUI from scratch: declarative views, stacks and layout, modifiers, @State and @Binding, @Observable models, Lists, Forms, NavigationStack, sheets, and previews.
If you know basic Swift and want to build native apps for iPhone, iPad, and Mac, this guide is for you.
SwiftUI changes how you think about building user interfaces. Instead of creating buttons and labels by hand and mutating them one by one when something changes, you describe what your screen looks like for a given state, and SwiftUI keeps the screen in sync for you.
In this guide we start from zero. We create our first SwiftUI app in Xcode, learn views, modifiers, layout stacks, controls, state, @Observable, lists, navigation, forms, async networking, SwiftData persistence, animations, and multiplatform tips.
Every SwiftUI and Observation (@Observable) snippet in this guide was checked against Apple Swift 6.4.2 on macOS.
| Software | Version |
|---|---|
Swift (swiftc) | Apple Swift 6.4.2 |
| UI Framework | SwiftUI (iOS 17+ / macOS 14+ modern Observation APIs) |
| Persistence | SwiftData + @AppStorage |
What is SwiftUI?
SwiftUI is Apple’s modern framework for building apps across iOS, macOS, iPadOS, watchOS, and visionOS using Swift.
Before SwiftUI, Apple developers built interfaces with UIKit (on iOS) or AppKit (on macOS). In those frameworks you wrote imperative code: grab a label reference, update label.text, hide a spinner, change a constraint, and hope you did not forget any screen state.
SwiftUI is declarative. You declare what your view looks like as a function of your data. When your data changes, SwiftUI recomputes your view description, compares it with what is already on screen, and updates only the pieces that changed.
Here is a complete SwiftUI screen in ten lines of Swift:
import SwiftUI
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 16) {
Text("Count: \(count)")
.font(.title)
Button("Add one") {
count += 1
}
}
.padding()
}
}
Look closely at what happens when we tap Add one. We never touch the Text view directly. We only run count += 1, and SwiftUI notices that count changed and updates the text on screen automatically.
Notice also that CounterView is a struct, not a class. I found that strange when I moved over from UIKit, because SwiftUI views are lightweight value types that SwiftUI can create and discard thousands of times a second without hurting performance.
Creating your first SwiftUI app in Xcode
Let’s get a working app on screen right away.
Open Xcode on your Mac and pick File > New > Project. Choose App under iOS (or Multiplatform if you want iOS and macOS from one codebase), set Interface to SwiftUI and Language to Swift, and give your project a name like BookTracker.
Xcode creates two Swift files for you right out of the box.
The first file is your app entry point, marked with @main:
import SwiftUI
@main
struct BookTrackerApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@main tells Swift where your app starts. WindowGroup creates a standard window for your platform (a full-screen app on iPhone, or resizable windows on iPad and Mac) and places ContentView() inside it.
The second file is ContentView.swift, where your first screen lives:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 12) {
Image(systemName: "book.closed")
.font(.largeTitle)
.foregroundStyle(.blue)
Text("Hello, SwiftUI!")
.font(.title2)
}
.padding()
}
}
#Preview {
ContentView()
}
The #Preview macro at the bottom renders your view live inside Xcode’s Canvas pane as you type, without waiting for a full simulator launch. Press Option + Command + P whenever the preview pauses, and press Command + R when you want to run the app in the iOS Simulator or on your Mac.
What some View means
Every SwiftUI view has a body property returning some View.
That some keyword is an opaque return type. It tells the Swift compiler “this body returns one specific concrete view type, please figure out the messy nested type for me so I do not have to write VStack<TupleView<(Image, Text)>> by hand.”
One rule I always keep in mind: body must return a single view. Whenever we want to show two or more views, we wrap them in a container like VStack, HStack, ZStack, List, or Group.
Views, modifiers, and why order matters
Everything we see on screen in SwiftUI is a View: text, images, buttons, shapes, and layout containers. We customize views by chaining modifiers on them with dot syntax.
Displaying text with Text
Text displays read-only strings and automatically supports Dynamic Type so our app respects the user’s preferred text size:
Text("SwiftUI Handbook")
.font(.title)
.fontWeight(.bold)
.foregroundStyle(.primary)
.multilineTextAlignment(.center)
.lineLimit(2)
Text also renders basic inline Markdown out of the box:
Text("Read **Chapter 3** or visit [flaviocopes.com](https://flaviocopes.com).")
Showing icons and images with Image and Label
Apple ships thousands of crisp vector icons called SF Symbols (I browse them constantly with Apple’s free SF Symbols Mac app). We can show any symbol with Image(systemName:):
Image(systemName: "star.fill")
.font(.title2)
.foregroundStyle(.yellow)
For photos or custom PNGs added to our Xcode Assets catalog, we load them by name and add .resizable() before setting a frame so the image scales instead of overflowing the screen:
Image("milan-skyline")
.resizable()
.scaledToFill()
.frame(width: 240, height: 160)
.clipShape(RoundedRectangle(cornerRadius: 12))
When you want an icon next to text (especially in lists, menus, and toolbars), use Label. SwiftUI handles spacing, baseline alignment, and accessibility automatically:
Label("Favorites", systemImage: "heart.fill")
.font(.headline)
.foregroundStyle(.pink)
Why modifier order matters
This is the first real SwiftUI “aha!” moment.
Every modifier wraps the previous view in a new view. That means the order you chain modifiers changes the visual result.
Compare these two examples:
// Padding first, then background: blue box wraps the padded space
Text("Save")
.padding()
.background(.blue)
.foregroundStyle(.white)
// Background first, then padding: tight blue box, empty space outside it
Text("Save")
.background(.blue)
.padding()
In the first example, .padding() expands the view’s box first, and .background(.blue) paints the whole padded area blue. In the second example, .background(.blue) paints only the tight text rectangle, and .padding() adds invisible space around the outside.
Think of modifiers as wrapping a gift box from the inside out: inner modifiers apply to the view first, and outer modifiers wrap everything before them.
Layout with stacks, grids, and spacers
SwiftUI lays out screens by composing simple containers rather than writing pixel coordinates or Auto Layout constraints.
VStack, HStack, and ZStack
You will build 90% of your layouts with three stacks:
VStackarranges child views vertically from top to bottom.HStackarranges child views horizontally from leading to trailing.ZStacklayers child views on top of each other along the depth axis (back to front).
VStack(alignment: .leading, spacing: 8) {
HStack {
Image(systemName: "cup.and.saucer.fill")
.foregroundStyle(.brown)
Text("Morning Espresso")
.font(.headline)
Spacer()
Text("$3.50")
.foregroundStyle(.secondary)
}
Text("Single origin beans roasted in Milan.")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.padding()
.background(.thinMaterial)
.clipShape(RoundedRectangle(cornerRadius: 12))
Notice Spacer() inside the HStack. A Spacer expands to fill all remaining empty space along the stack’s axis, pushing the price cleanly to the trailing edge.
Controlling size with .frame()
By default, SwiftUI views hug their content tightly (like Text) or expand to fill available space (like Color and Spacer).
Use .frame() when you want fixed dimensions or flexible full-width alignment:
Text("Continue")
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
.background(.blue)
.foregroundStyle(.white)
.clipShape(RoundedRectangle(cornerRadius: 10))
maxWidth: .infinity stretches the label across the whole width of its parent container, which is how you build full-width buttons and cards cleanly on every screen size.
Grids and scrolling
Wrap tall content in ScrollView when it can exceed the screen height.
When you have hundreds or thousands of items, switch from VStack to LazyVStack (or LazyVGrid) inside a ScrollView. Regular stacks create every child view upfront, while lazy stacks create views only as they scroll onto the screen:
struct PhotoGridView: View {
let columns = [
GridItem(.adaptive(minimum: 120), spacing: 12)
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 12) {
ForEach(1..<31) { index in
RoundedRectangle(cornerRadius: 10)
.fill(.blue.gradient)
.frame(height: 100)
.overlay {
Text("#\(index)")
.foregroundStyle(.white)
.font(.headline)
}
}
}
.padding()
}
}
}
For small static tables or aligned two-dimensional layouts (like a settings card or calculator), SwiftUI also includes a non-lazy Grid with GridRow views.
Choosing the right layout container
| Container | Direction / behavior | Best for |
|---|---|---|
VStack | Vertical, loads all children | Cards, short forms, small screens |
HStack | Horizontal, loads all children | Rows, headers, button bars |
ZStack | Layered back-to-front | Badges, overlays, background gradients |
LazyVStack / LazyHStack | Vertical / horizontal, loads on demand | Long scrollable feeds inside ScrollView |
LazyVGrid / LazyHGrid | Multi-column or multi-row, on demand | Photo galleries, icon grids |
List | Scrollable rows with system styling | Settings screens, inbox rows, swipe actions |
Buttons, controls, and user input
SwiftUI ships native controls that automatically adapt to iPhone, iPad, and Mac conventions.
Button and button styles
A Button takes an action closure and a label view:
Button {
print("Book saved")
} label: {
Label("Save Book", systemImage: "bookmark.fill")
}
.buttonStyle(.borderedProminent)
Built-in styles include .plain, .bordered, .borderedProminent, and .borderless. For destructive actions like deleting an item, pass role: .destructive so iOS and macOS tint the button red automatically:
Button("Delete Draft", role: .destructive) {
deleteDraft()
}
TextField and SecureField
Input controls need a two-way binding (prefixed with $) to a @State variable so the control can both display and update the value:
struct LoginFieldsView: View {
@State private var email = ""
@State private var password = ""
var body: some View {
VStack(spacing: 12) {
TextField("Email address", text: $email)
.textFieldStyle(.roundedBorder)
.textInputAutocapitalization(.never)
.keyboardType(.emailAddress)
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)
}
.padding()
}
}
Toggle, Slider, Stepper, and Picker
Every other built-in control follows the same $binding pattern:
struct ReaderSettingsView: View {
@State private var darkPaper = false
@State private var fontSize = 16.0
@State private var dailyGoal = 20
@State private var theme = "Warm"
let themes = ["Light", "Warm", "Dark"]
var body: some View {
Form {
Toggle("Dark paper mode", isOn: $darkPaper)
VStack(alignment: .leading) {
Text("Font size: \(Int(fontSize)) pt")
Slider(value: $fontSize, in: 12...28, step: 1)
}
Stepper("Daily goal: \(dailyGoal) pages", value: $dailyGoal, in: 5...100, step: 5)
Picker("Theme", selection: $theme) {
ForEach(themes, id: \.self) { option in
Text(option)
}
}
.pickerStyle(.segmented)
}
}
}
Notice how clean that is. You never write onChange listeners just to keep a switch or slider synced with your variables.
State and data flow
State is the beating heart of SwiftUI. Getting data flow right early makes every screen you build ten times simpler.
Local view state with @State
Because SwiftUI views are structs, you cannot normally mutate a property inside body. Marking a property with @State asks SwiftUI to store that value outside the struct so it survives view re-renders and triggers a UI refresh whenever it changes.
Always mark @State properties private to remind yourself that this view owns the data:
struct FavoriteButton: View {
@State private var isFavorite = false
var body: some View {
Button {
isFavorite.toggle()
} label: {
Image(systemName: isFavorite ? "heart.fill" : "heart")
.foregroundStyle(isFavorite ? .red : .secondary)
}
}
}
Passing read-only data down
When a child view only needs to display data, pass a plain let property. No property wrapper needed:
struct BookRow: View {
let title: String
let pages: Int
var body: some View {
HStack {
Text(title)
Spacer()
Text("\(pages) pages")
.foregroundStyle(.secondary)
}
}
}
Passing editable state down with @Binding
When a child view needs to change state owned by its parent, pass a @Binding. The parent owns the single source of truth with @State and hands the child a two-way link using $:
struct MuteToggle: View {
@Binding var isMuted: Bool
var body: some View {
Button(isMuted ? "Unmute" : "Mute") {
isMuted.toggle()
}
}
}
struct AudioBar: View {
@State private var isMuted = false
var body: some View {
HStack {
Text(isMuted ? "Sound off" : "Sound on")
Spacer()
MuteToggle(isMuted: $isMuted)
}
.padding()
}
}
There is only one boolean (isMuted in AudioBar). Both views stay in lockstep automatically because nobody copied the value into a second @State.
Sharing state with @Observable and @Environment
@State and @Binding work great for simple values like booleans, strings, and counters. Once your app has real models (a task list, shopping cart, or logged-in user shared across multiple screens), you want an observable class.
Modern observation with @Observable
Since iOS 17 and macOS 14, Swift’s Observation framework replaces the older ObservableObject / @Published / @StateObject boilerplate with a single @Observable macro.
You import Observation, put @Observable on a regular Swift class, and SwiftUI tracks only the specific properties each view actually reads:
import Observation
import SwiftUI
struct TaskItem: Identifiable {
let id = UUID()
var title: String
var isDone = false
}
@Observable
final class TaskStore {
var items: [TaskItem] = [
TaskItem(title: "Read SwiftUI Handbook"),
TaskItem(title: "Build first iOS prototype"),
]
var remainingCount: Int {
items.filter { !$0.isDone }.count
}
func add(_ title: String) {
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
items.append(TaskItem(title: trimmed))
}
}
Store the @Observable instance in @State inside the root view that owns it:
struct TasksView: View {
@State private var store = TaskStore()
@State private var draftTitle = ""
var body: some View {
NavigationStack {
List {
Section("Remaining: \(store.remainingCount)") {
ForEach(store.items) { item in
Text(item.title)
}
}
}
.navigationTitle("Tasks")
.safeAreaInset(edge: .bottom) {
HStack {
TextField("New task", text: $draftTitle)
.textFieldStyle(.roundedBorder)
Button("Add") {
store.add(draftTitle)
draftTitle = ""
}
}
.padding()
.background(.bar)
}
}
}
}
Here is Apple Swift 6.4.2 typechecking this @Observable + SwiftUI view cleanly from the terminal:

Creating bindings to @Observable properties with @Bindable
When you pass an @Observable object into a child view and want to bind a TextField or Toggle directly to one of its properties, mark the parameter @Bindable:
struct TaskEditor: View {
@Bindable var store: TaskStore
var body: some View {
List($store.items) { $item in
Toggle(item.title, isOn: $item.isDone)
}
}
}
Sharing across many screens with @Environment
If five nested screens all need access to TaskStore, passing it manually through every initializer gets tedious. Inject it once near the top of your app with .environment(), and read it anywhere below with @Environment:
@main
struct TasksApp: App {
@State private var store = TaskStore()
var body: some Scene {
WindowGroup {
ContentView()
.environment(store)
}
}
}
struct SummaryBadge: View {
@Environment(TaskStore.self) private var store
var body: some View {
Text("\(store.remainingCount) left")
.font(.caption)
}
}
SwiftUI also exposes built-in system environment values like \.colorScheme, \.dismiss, \.openURL, and \.accessibilityReduceMotion.
State property wrappers at a glance
| Wrapper | Owns the data? | Use it for |
|---|---|---|
@State | Yes | Local value types (Int, String, Bool) or root @Observable models |
@Binding | No | Two-way link to a parent’s @State value |
@Observable | Class macro | Shared reference-type data models (replaces ObservableObject + @Published) |
@Bindable | No | Creating $ bindings to properties of a passed-in @Observable model |
@Environment | No | Reading app-wide models or system values (\.dismiss, \.colorScheme) |
@AppStorage | UserDefaults | Small persisted preferences (theme, onboarding flag, sort order) |
Conditional views, lists, and ForEach
Real screens change shape depending on your data: empty states, search results, grouped lists, and swipe-to-delete rows.
Conditional rendering with if and switch
Inside a view’s body, you can use normal Swift if, if let, and switch statements:
struct ProfileHeader: View {
let username: String?
var body: some View {
if let username {
Label(username, systemImage: "person.circle.fill")
.font(.headline)
} else {
Text("Guest")
.foregroundStyle(.secondary)
}
}
}
Keep one performance habit in mind: if you only want to change a color or opacity based on a condition, use a ternary operator inside the modifier (.opacity(isDimmed ? 0.4 : 1)) instead of an if/else that destroys and recreates the whole view.
ForEach and Identifiable
ForEach loops over a collection to create views dynamically. SwiftUI needs a stable ID for every element so it knows which rows were inserted, moved, or deleted during animations.
The cleanest approach is conforming your model struct to Identifiable by giving it an id property:
struct Book: Identifiable {
let id = UUID()
let title: String
let author: String
}
Now ForEach works without passing an explicit id: parameter:
ForEach(books) { book in
VStack(alignment: .leading) {
Text(book.title).font(.headline)
Text(book.author).font(.subheadline).foregroundStyle(.secondary)
}
}
For simple arrays of strings or numbers where each value is unique, pass id: \.self:
ForEach(["Swift", "SwiftUI", "SwiftData"], id: \.self) { topic in
Text(topic)
}
Never use array indices (0..<items.count) as IDs for mutable lists, or SwiftUI will glitch or crash when you delete a row.
List, sections, swipe actions, and .searchable
List wraps rows in the native scrolling list style for each Apple platform and gives you sections, swipe-to-delete, and search bars in a few lines:
struct LibraryView: View {
@State private var books = [
Book(title: "Swift Handbook", author: "Flavio Copes"),
Book(title: "SwiftUI Handbook", author: "Flavio Copes"),
Book(title: "TypeScript Handbook", author: "Flavio Copes"),
]
@State private var query = ""
var filteredBooks: [Book] {
if query.isEmpty { return books }
return books.filter { $0.title.localizedCaseInsensitiveContains(query) }
}
var body: some View {
NavigationStack {
List {
Section("My Books") {
ForEach(filteredBooks) { book in
VStack(alignment: .leading) {
Text(book.title).font(.headline)
Text(book.author).font(.caption).foregroundStyle(.secondary)
}
}
.onDelete { offsets in
books.remove(atOffsets: offsets)
}
}
}
.navigationTitle("Library")
.searchable(text: $query, prompt: "Search books")
}
}
}
For custom swipe buttons (like Archive or Pin alongside Delete), attach .swipeActions directly to each row view inside ForEach.
Navigation with NavigationStack and TabView
Most real apps have more than one screen. SwiftUI handles both drill-down stacks and multi-tab layouts cleanly.
Value-based navigation with NavigationStack
Wrap your root screen in a NavigationStack. Instead of creating destination views upfront inside every row, pass a value to NavigationLink(value:) and resolve the destination once with .navigationDestination(for:).
Your model only needs to conform to Hashable:
import SwiftUI
struct Recipe: Identifiable, Hashable {
let id = UUID()
let title: String
let minutes: Int
}
struct RecipeListView: View {
let recipes = [
Recipe(title: "Pesto Pasta", minutes: 15),
Recipe(title: "Risotto alla Milanese", minutes: 35),
]
var body: some View {
NavigationStack {
List(recipes) { recipe in
NavigationLink(value: recipe) {
HStack {
Text(recipe.title)
Spacer()
Text("\(recipe.minutes) min")
.foregroundStyle(.secondary)
}
}
}
.navigationTitle("Recipes")
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetailView(recipe: recipe)
}
}
}
}
struct RecipeDetailView: View {
let recipe: Recipe
var body: some View {
VStack(spacing: 12) {
Text(recipe.title).font(.largeTitle)
Text("Ready in \(recipe.minutes) minutes")
.foregroundStyle(.secondary)
}
.navigationTitle(recipe.title)
.navigationBarTitleDisplayMode(.inline)
}
}
Programmatic navigation with NavigationPath
When you need to push a screen from code (for example, opening a deep link or jumping straight back to the root screen), bind NavigationStack(path:) to a @State private var path = NavigationPath():
struct RootView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
VStack(spacing: 16) {
Button("Jump to Pesto") {
path.append(Recipe(title: "Pesto Pasta", minutes: 15))
}
}
.navigationDestination(for: Recipe.self) { recipe in
VStack(spacing: 16) {
Text(recipe.title).font(.title)
Button("Back to root") {
path = NavigationPath()
}
}
}
}
}
}
Clearing path = NavigationPath() pops every pushed screen in one line.
Tabs with TabView
When your app has two to five independent top-level sections, wrap them in a TabView (with each tab owning its own NavigationStack):
struct MainTabView: View {
var body: some View {
TabView {
Tab("Library", systemImage: "books.vertical") {
LibraryView()
}
Tab("Favorites", systemImage: "heart") {
FavoritesView()
}
Tab("Settings", systemImage: "gearshape") {
ReaderSettingsView()
}
}
}
}
Sheets, alerts, and confirmation dialogs
Some interactions belong in a temporary overlay rather than a pushed navigation screen: creating a new item, picking an option, or confirming a deletion.
Modal sheets and @Environment(\.dismiss)
Present a sheet by binding .sheet(isPresented:) to a boolean, or .sheet(item:) to an optional Identifiable model. Inside the sheet, use @Environment(\.dismiss) to close it cleanly:
struct NewNoteSheet: View {
@Environment(\.dismiss) private var dismiss
@State private var text = ""
let onSave: (String) -> Void
var body: some View {
NavigationStack {
Form {
TextField("Write a quick note", text: $text, axis: .vertical)
.lineLimit(3...6)
}
.navigationTitle("New Note")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button("Save") {
onSave(text)
dismiss()
}
.disabled(text.trimmingCharacters(in: .whitespaces).isEmpty)
}
}
}
}
}
Attach the sheet to any parent view:
.sheet(isPresented: $showingComposer) {
NewNoteSheet { note in
notes.append(note)
}
.presentationDetents([.medium, .large])
}
.presentationDetents([.medium, .large]) lets the sheet open at half-screen height and smoothly drag up to full height.
Alerts and confirmation dialogs
Use .alert for short critical confirmations and .confirmationDialog for multi-option action sheets:
Button("Delete All Notes", role: .destructive) {
showingDeleteAlert = true
}
.alert("Delete all notes?", isPresented: $showingDeleteAlert) {
Button("Delete", role: .destructive) {
notes.removeAll()
}
Button("Cancel", role: .cancel) {}
} message: {
Text("This removes every saved note and cannot be undone.")
}
Forms, validation, and focus management
SwiftUI’s Form container automatically styles inputs, toggles, pickers, and buttons into crisp grouped sections on iOS and aligned label-control rows on macOS.
Managing keyboard focus with @FocusState
@FocusState lets you move the cursor between fields when the user taps the Return key or dismiss the keyboard programmatically:
import SwiftUI
struct SignupFormView: View {
enum Field {
case name
case email
}
@State private var name = ""
@State private var email = ""
@FocusState private var focusedField: Field?
var isValid: Bool {
!name.trimmingCharacters(in: .whitespaces).isEmpty && email.contains("@")
}
var body: some View {
Form {
Section("Your details") {
TextField("Full name", text: $name)
.focused($focusedField, equals: .name)
.submitLabel(.next)
.onSubmit { focusedField = .email }
TextField("Email", text: $email)
.focused($focusedField, equals: .email)
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
.submitLabel(.done)
.onSubmit { focusedField = nil }
}
Section {
Button("Create Account") {
focusedField = nil
print("Submitted \(name) <\(email)>")
}
.disabled(!isValid)
}
}
}
}
Setting focusedField = nil hides the software keyboard on iPhone and iPad right away.
Working with async data and .task
Modern Swift uses async and await for networking and background work, and SwiftUI integrates directly with it through the .task modifier.
Modeling loading, loaded, and error states
Before writing your network call, define a small enum for every state the screen can be in. That way you can never accidentally show a spinner and an error banner at the same time:
import SwiftUI
struct Post: Codable, Identifiable {
let id: Int
let title: String
}
enum LoadState<Value> {
case loading
case loaded(Value)
case failed(String)
}
struct PostsView: View {
@State private var state: LoadState<[Post]> = .loading
var body: some View {
NavigationStack {
Group {
switch state {
case .loading:
ProgressView("Loading posts...")
case .loaded(let posts):
List(posts) { post in
Text(post.title)
}
.refreshable {
await loadPosts()
}
case .failed(let message):
ContentUnavailableView {
Label("Could not load posts", systemImage: "wifi.slash")
} description: {
Text(message)
} actions: {
Button("Try Again") {
Task { await loadPosts() }
}
}
}
}
.navigationTitle("Posts")
.task {
await loadPosts()
}
}
}
private func loadPosts() async {
state = .loading
do {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts?_limit=10")!
let (data, _) = try await URLSession.shared.data(from: url)
let decoded = try JSONDecoder().decode([Post].self, from: data)
state = .loaded(decoded)
} catch {
if Task.isCancelled { return }
state = .failed(error.localizedDescription)
}
}
}
Why use .task instead of .onAppear { Task { ... } }? Because .task automatically cancels your in-flight network request if the user navigates away before it finishes.
If you need the task to re-run whenever a search query or selected filter changes, pass .task(id: selectedCategory) and SwiftUI cancels the old task and starts a fresh one automatically.
Persistence with @AppStorage and SwiftData
Once your app closes, @State resets. For data that needs to survive app restarts, SwiftUI gives you two great built-in options depending on how structured the data is.
Simple preferences with @AppStorage
For lightweight user settings (a boolean flag, selected theme, or preferred font size), @AppStorage reads and writes straight to UserDefaults and updates your view automatically:
struct PreferencesView: View {
@AppStorage("showCompletedTasks") private var showCompleted = true
@AppStorage("readerFontSize") private var fontSize = 16.0
var body: some View {
Form {
Toggle("Show completed tasks", isOn: $showCompleted)
Slider(value: $fontSize, in: 12...28, step: 1)
}
}
}
Never store secrets, passwords, or large datasets in @AppStorage. Use Keychain for secrets and SwiftData (or SQLite) for structured collections.
Structured data with SwiftData
SwiftData persists Swift classes to an on-device SQLite store with almost zero setup. Mark your model class with @Model:
import SwiftData
import SwiftUI
@Model
final class Bookmark {
var title: String
var url: String
var createdAt: Date
init(title: String, url: String) {
self.title = title
self.url = url
self.createdAt = .now
}
}
Attach .modelContainer(for: Bookmark.self) at the root of your app:
@main
struct BookmarksApp: App {
var body: some Scene {
WindowGroup {
BookmarksView()
}
.modelContainer(for: Bookmark.self)
}
}
Inside any view, fetch live sorted records with @Query and insert or delete through @Environment(\.modelContext):
struct BookmarksView: View {
@Environment(\.modelContext) private var context
@Query(sort: \Bookmark.createdAt, order: .reverse) private var bookmarks: [Bookmark]
var body: some View {
NavigationStack {
List {
ForEach(bookmarks) { item in
VStack(alignment: .leading) {
Text(item.title).font(.headline)
Text(item.url).font(.caption).foregroundStyle(.secondary)
}
}
.onDelete { offsets in
for index in offsets {
context.delete(bookmarks[index])
}
}
}
.navigationTitle("Bookmarks")
.toolbar {
Button("Add", systemImage: "plus") {
context.insert(Bookmark(title: "Flavio Copes", url: "https://flaviocopes.com"))
}
}
}
}
}
When you insert or delete a Bookmark, SwiftData saves to disk and @Query refreshes the List automatically.
Animations and transitions
In SwiftUI, you animate state changes rather than calculating frames by hand.
Explicit animations with withAnimation
Wrap a state change inside withAnimation and SwiftUI smoothly interpolates every visual change caused by that state:
struct ExpandableCard: View {
@State private var isExpanded = false
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Button {
withAnimation(.snappy) {
isExpanded.toggle()
}
} label: {
HStack {
Text("Details")
.font(.headline)
Spacer()
Image(systemName: "chevron.right")
.rotationEffect(.degrees(isExpanded ? 90 : 0))
}
}
.buttonStyle(.plain)
if isExpanded {
Text("SwiftUI interpolates layout, opacity, and rotation automatically.")
.font(.subheadline)
.foregroundStyle(.secondary)
.transition(.opacity.combined(with: .move(edge: .top)))
}
}
.padding()
.background(.thinMaterial)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
Implicit animations and Reduce Motion
You can also attach .animation(.easeInOut(duration: 0.25), value: count) directly to a view so it animates only when count changes.
Always respect users who have enabled Reduce Motion in system accessibility settings:
@Environment(\.accessibilityReduceMotion) private var reduceMotion
Button("Toggle") {
if reduceMotion {
isExpanded.toggle()
} else {
withAnimation(.snappy) {
isExpanded.toggle()
}
}
}
Checking accessibilityReduceMotion takes four lines and makes your app genuinely comfortable for people who get motion sickness from sliding animations.
Building for macOS, iPadOS, and multiplatform apps
One of SwiftUI’s biggest wins is writing one core codebase that feels truly native on iPhone, iPad, and Mac.
Sidebar layouts with NavigationSplitView
On iPad and Mac, users expect a sidebar next to the detail view rather than a full-width drill-down list. NavigationSplitView gives you a sidebar on wide screens and automatically collapses into a single-column stack on iPhone:
struct NotesSplitView: View {
let folders = ["Inbox", "Reading List", "Archive"]
@State private var selectedFolder: String? = "Inbox"
var body: some View {
NavigationSplitView {
List(folders, id: \.self, selection: $selectedFolder) { folder in
Label(folder, systemImage: "folder")
}
.navigationTitle("Folders")
} detail: {
if let selectedFolder {
Text("Showing \(selectedFolder)")
.font(.title2)
} else {
ContentUnavailableView("Select a folder", systemImage: "sidebar.left")
}
}
}
}
Native Mac touches (Settings and menu bar commands)
On macOS, add a native Preferences window (Command + ,) using a Settings scene right beside your WindowGroup, and add menu bar keyboard shortcuts with .commands:
@main
struct MultiplatformApp: App {
var body: some Scene {
WindowGroup {
NotesSplitView()
}
.commands {
CommandGroup(after: .newItem) {
Button("Quick Note") {
print("Open quick note")
}
.keyboardShortcut("n", modifiers: [.command, .shift])
}
}
#if os(macOS)
Settings {
ReaderSettingsView()
.frame(width: 420, height: 260)
}
#endif
}
}
Custom modifiers, ViewBuilders, and reusable button styles
Once our app grows past three screens, copying .padding(), .background(), .clipShape(), and .shadow() onto twenty cards gets messy fast.
SwiftUI gives us three clean tools for building our own design system without fighting the framework.
Creating a custom ViewModifier
If we repeat the same chain of modifiers across multiple views, wrap it in a ViewModifier struct and expose a short helper on View:
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding(16)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.background.secondary)
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(.separator, lineWidth: 1)
)
}
}
extension View {
func cardStyle() -> some View {
modifier(CardStyle())
}
}
Now any screen in our app applies that entire surface treatment in one readable line:
VStack(alignment: .leading, spacing: 6) {
Text("SwiftUI Handbook")
.font(.headline)
Text("Updated for Swift 6")
.foregroundStyle(.secondary)
}
.cardStyle()
Building container views with @ViewBuilder
What if we want a reusable wrapper view (like a titled section card) that accepts any child views inside curly braces, just like VStack does?
Mark the closure property with @ViewBuilder:
struct SectionCard<Content: View>: View {
let title: String
@ViewBuilder let content: () -> Content
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text(title)
.font(.subheadline)
.fontWeight(.semibold)
.foregroundStyle(.secondary)
content()
}
.cardStyle()
}
}
Now we can drop arbitrary SwiftUI views inside SectionCard:
SectionCard(title: "Reading goal") {
Text("12 books this year")
.font(.title3.bold())
ProgressView(value: 0.5)
}
Consistent press feedback with ButtonStyle
To give every primary button in our app the same springy press scale without duplicating animation code, implement ButtonStyle:
struct PrimaryButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.headline)
.foregroundStyle(.white)
.padding(.horizontal, 20)
.padding(.vertical, 12)
.background(.tint, in: RoundedRectangle(cornerRadius: 12, style: .continuous))
.scaleEffect(configuration.isPressed ? 0.97 : 1.0)
.opacity(configuration.isPressed ? 0.9 : 1.0)
.animation(.spring(duration: 0.18), value: configuration.isPressed)
}
}
Apply it to one button with .buttonStyle(PrimaryButtonStyle()), or apply it to an entire parent container so every button inside inherits it automatically.
Gestures, scroll control, and pull-to-refresh
Standard buttons and lists cover most interactions, and SwiftUI also makes custom gestures, programmatic scrolling, search bars, and pull-to-refresh straightforward.
Taps, long presses, and DragGesture with @GestureState
For simple taps or double-taps, attach .onTapGesture(count: 2) directly to a view.
For dragging a card or swiping a drawer, reach for DragGesture paired with @GestureState. The big advantage of @GestureState over plain @State is that SwiftUI automatically resets it back to its initial value the instant the finger lifts (even if a system alert interrupts the gesture!):
struct DraggableCard: View {
@GestureState private var dragOffset: CGSize = .zero
var body: some View {
RoundedRectangle(cornerRadius: 18, style: .continuous)
.fill(.blue.gradient)
.frame(width: 240, height: 140)
.overlay(Text("Drag me").foregroundStyle(.white).font(.headline))
.offset(dragOffset)
.animation(.spring(duration: 0.3), value: dragOffset)
.gesture(
DragGesture()
.updating($dragOffset) { value, state, _ in
state = value.translation
}
)
}
}
Notice .animation(..., value: dragOffset) smoothly springs the card right back to center as soon as we let go.
Programmatic scrolling and snapping carousels
Wrap a ScrollView in ScrollViewReader whenever we want a button to jump directly to a specific row by ID (such as a “Jump to bottom” button in a chat view):
struct LogScrollView: View {
let entries = Array(1...50)
var body: some View {
ScrollViewReader { proxy in
VStack {
Button("Jump to #50") {
withAnimation {
proxy.scrollTo(50, anchor: .bottom)
}
}
ScrollView {
LazyVStack(spacing: 8) {
ForEach(entries, id: \.self) { number in
Text("Log entry #\(number)")
.id(number)
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(.background.secondary, in: RoundedRectangle(cornerRadius: 8))
}
}
.padding()
}
}
}
}
}
For horizontal card carousels that snap cleanly to each card on iOS 17+ and macOS 14+, combine .scrollTargetLayout() on the LazyHStack with .scrollTargetBehavior(.viewAligned) on the ScrollView.
Built-in .searchable and .refreshable
Two modifiers save hours of boilerplate on list screens:
.searchable(text: $query, prompt: "Search books")places a native search bar in the navigation bar on iOS and in the toolbar on macOS..refreshable { await store.reload() }adds native pull-to-refresh to anyListorScrollViewand keeps the spinner visible until ourasyncfunction completes.
List(filteredBooks) { book in
Text(book.title)
}
.searchable(text: $query, prompt: "Filter titles")
.refreshable {
await store.refreshFromServer()
}
Custom shapes, Canvas, and Swift Charts
Sometimes standard rectangles and SF Symbols are not enough. SwiftUI lets us draw vector shapes, render fast 2D graphics with Canvas, and build native charts with Apple’s Charts framework.
Drawing custom vector shapes with Shape and Path
Conform to the Shape protocol and implement path(in rect: CGRect) to draw crisp, resolution-independent shapes that work with .fill(), .stroke(), and .clipShape():
struct TriangleBadge: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.closeSubpath()
return path
}
}
When you need to draw hundreds of moving particles, waveforms, or sparklines at 60 frames per second, use Canvas { context, size in ... } instead of creating hundreds of separate SwiftUI Circle() views. Canvas draws directly into Core Graphics without building a huge view hierarchy.
Native charts with Charts
Apple ships the Charts framework right inside iOS 16+ and macOS 13+. I love using it for analytics and habit trackers because VoiceOver support, Dark Mode colors, and clean axis labels work automatically:
import Charts
import SwiftUI
struct ReadingDay: Identifiable {
let id = UUID()
let day: String
let pages: Int
}
struct ReadingChartView: View {
let data = [
ReadingDay(day: "Mon", pages: 22),
ReadingDay(day: "Tue", pages: 35),
ReadingDay(day: "Wed", pages: 18),
ReadingDay(day: "Thu", pages: 44),
ReadingDay(day: "Fri", pages: 30),
]
var body: some View {
Chart(data) { item in
BarMark(
x: .value("Day", item.day),
y: .value("Pages", item.pages)
)
.foregroundStyle(.blue.gradient)
.cornerRadius(6)
}
.frame(height: 200)
.padding()
}
}
Swap BarMark for LineMark or AreaMark to turn the same dataset into a trend line in one word.
Accessibility, Dynamic Type, and Dark Mode
Apple’s platforms care deeply about accessibility, and building accessible SwiftUI screens takes only a handful of habits when we do it as we go.
VoiceOver labels and grouping
Icon-only buttons need a spoken label so VoiceOver does not just say "Button":
Button {
toggleBookmark()
} label: {
Image(systemName: isBookmarked ? "bookmark.fill" : "bookmark")
}
.accessibilityLabel(isBookmarked ? "Remove bookmark" : "Bookmark book")
.accessibilityHint("Saves this book to your reading list")
When a card displays three separate Text views (title, author, and page count), group them with .accessibilityElement(children: .combine) so VoiceOver reads the whole card in one natural swipe instead of forcing the user to swipe three times per row.
Scaling custom spacing with @ScaledMetric
Standard fonts like .body and .headline automatically grow when a user increases their Dynamic Type text size in System Settings.
If we have a custom icon width or badge height that should grow proportionally alongside the text, declare it with @ScaledMetric instead of hardcoding 24:
struct StatusBadge: View {
@ScaledMetric(relativeTo: .body) private var dotSize: CGFloat = 10
var body: some View {
HStack(spacing: 8) {
Circle()
.fill(.green)
.frame(width: dotSize, height: dotSize)
Text("Synced")
.font(.body)
}
}
}
Automatic Dark Mode without extra code
Never hardcode Color.black for text or Color.white for backgrounds unless you truly want fixed colors regardless of appearance.
Instead, rely on semantic styles (.primary, .secondary, .tint, .background) and create named Color Sets in Xcode’s Assets.xcassets with distinct Any Appearance and Dark swatches. We can preview both modes together by adding .preferredColorScheme(.dark) to a second #Preview block.
Bridging UIKit and AppKit when needed
SwiftUI covers almost every interface you will build today, and occasionally you still need a battle-tested UIKit or AppKit view that SwiftUI does not wrap natively yet (like WKWebView on older OS targets, PDFView, or a custom NSTextView editor).
SwiftUI lets us wrap any UIKit view using UIViewRepresentable (or NSViewRepresentable on macOS) in about twenty lines:
#if canImport(UIKit)
import SwiftUI
import WebKit
struct EmbeddedWebView: UIViewRepresentable {
let url: URL
func makeUIView(context: Context) -> WKWebView {
WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
if webView.url != url {
webView.load(URLRequest(url: url))
}
}
}
#endif
Look closely at that if webView.url != url check inside updateUIView. SwiftUI calls updateUIView whenever any parent state changes, so guarding against redundant reloads stops the web view from flickering back to the top on unrelated UI updates!
Whenever the wrapped UIKit/AppKit view communicates back via a delegate (like WKNavigationDelegate or UITextFieldDelegate), implement makeCoordinator() returning a small NSObject class that holds a reference to your SwiftUI bindings or callbacks.
Testing SwiftUI apps and Xcode Previews
Testing UI pixels directly is brittle and slow. The clean architectural habit I rely on in every SwiftUI app is putting business logic, validation, and async fetching into plain @Observable model classes, keeping SwiftUI View structs thin, and unit-testing those models directly with Swift Testing.
Testing @Observable logic with Swift Testing (@Test, #expect)
Swift 6 ships with the modern Swift Testing framework (import Testing), which is cleaner and faster than legacy XCTest:
import Testing
@Observable
final class ReadingGoalModel {
var booksRead = 0
var target = 12
var progress: Double {
guard target > 0 else { return 0 }
return min(Double(booksRead) / Double(target), 1.0)
}
func markFinished() {
booksRead += 1
}
}
@Test func progressCapsAtOneHundredPercent() {
let model = ReadingGoalModel()
model.target = 2
model.markFinished()
#expect(model.progress == 0.5)
model.markFinished()
model.markFinished()
#expect(model.progress == 1.0)
}
Those tests run in milliseconds with zero simulator boot time!
Better #Preview workflows (@Previewable and in-memory SwiftData)
Two modern Xcode preview features save tons of frustration:
@Previewable @Statelets us test interactive@Bindingchild views directly inside#Previewwithout writing a throwaway wrapper struct:
#Preview {
@Previewable @State var title = "SwiftUI Handbook"
TextField("Book title", text: $title)
.textFieldStyle(.roundedBorder)
.padding()
}
- In-memory SwiftData preview containers let us preview
@Queryscreens with realistic sample data without touching our real app database:
#Preview {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: ReadingItem.self, configurations: config)
container.mainContext.insert(ReadingItem(title: "SwiftUI Handbook", author: "Flavio Copes", pages: 48))
return ReadingListView()
.modelContainer(container)
}
Complete project: a multi-screen SwiftData Reading Tracker
Let’s bring everything we learned together into one clean, runnable SwiftUI 6 + SwiftData app: a Reading Tracker with persistent storage, search, status filtering, a sheet to add books, swipe-to-delete, and a detail screen to track pages read.
1. The SwiftData model (ReadingBook.swift)
import Foundation
import SwiftData
@Model
final class ReadingBook {
var title: String
var author: String
var totalPages: Int
var pagesRead: Int
var addedAt: Date
init(title: String, author: String, totalPages: Int, pagesRead: Int = 0) {
self.title = title
self.author = author
self.totalPages = max(totalPages, 1)
self.pagesRead = min(max(pagesRead, 0), max(totalPages, 1))
self.addedAt = .now
}
var isFinished: Bool {
pagesRead >= totalPages
}
var progress: Double {
Double(pagesRead) / Double(totalPages)
}
}
2. The app entry point (ReadingTrackerApp.swift)
import SwiftData
import SwiftUI
@main
struct ReadingTrackerApp: App {
var body: some Scene {
WindowGroup {
BookLibraryView()
}
.modelContainer(for: ReadingBook.self)
}
}
3. The main list, filter, and search screen (BookLibraryView.swift)
import SwiftData
import SwiftUI
enum BookFilter: String, CaseIterable, Identifiable {
case all = "All"
case reading = "Reading"
case finished = "Finished"
var id: String { rawValue }
}
struct BookLibraryView: View {
@Environment(\.modelContext) private var context
@Query(sort: \ReadingBook.addedAt, order: .reverse) private var books: [ReadingBook]
@State private var query = ""
@State private var filter: BookFilter = .all
@State private var showingAddSheet = false
private var visibleBooks: [ReadingBook] {
books.filter { book in
let matchesFilter = switch filter {
case .all: true
case .reading: !book.isFinished
case .finished: book.isFinished
}
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
let matchesQuery = trimmed.isEmpty
|| book.title.localizedCaseInsensitiveContains(trimmed)
|| book.author.localizedCaseInsensitiveContains(trimmed)
return matchesFilter && matchesQuery
}
}
var body: some View {
NavigationStack {
VStack(spacing: 0) {
Picker("Filter", selection: $filter) {
ForEach(BookFilter.allCases) { option in
Text(option.rawValue).tag(option)
}
}
.pickerStyle(.segmented)
.padding()
if visibleBooks.isEmpty {
ContentUnavailableView(
books.isEmpty ? "No books yet" : "No matching books",
systemImage: "books.vertical",
description: Text(books.isEmpty ? "Tap + to add your first book." : "Try a different search or filter.")
)
} else {
List {
ForEach(visibleBooks) { book in
NavigationLink(value: book) {
BookRowView(book: book)
}
}
.onDelete(perform: deleteBooks)
}
.listStyle(.plain)
}
}
.navigationTitle("Reading Tracker")
.searchable(text: $query, prompt: "Search title or author")
.navigationDestination(for: ReadingBook.self) { book in
BookDetailView(book: book)
}
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button("Add book", systemImage: "plus") {
showingAddSheet = true
}
}
}
.sheet(isPresented: $showingAddSheet) {
AddBookSheet()
}
}
}
private func deleteBooks(at offsets: IndexSet) {
for index in offsets {
context.delete(visibleBooks[index])
}
}
}
4. Row, detail view, and Add Book sheet (BookDetailView.swift)
import SwiftData
import SwiftUI
struct BookRowView: View {
let book: ReadingBook
var body: some View {
VStack(alignment: .leading, spacing: 6) {
HStack {
Text(book.title)
.font(.headline)
Spacer()
Text("\(Int(book.progress * 100))%")
.font(.caption.monospacedDigit())
.foregroundStyle(book.isFinished ? .green : .secondary)
}
Text(book.author)
.font(.subheadline)
.foregroundStyle(.secondary)
ProgressView(value: book.progress)
.tint(book.isFinished ? .green : .blue)
}
.padding(.vertical, 4)
.accessibilityElement(children: .combine)
}
}
struct BookDetailView: View {
@Bindable var book: ReadingBook
var body: some View {
Form {
Section("Book") {
TextField("Title", text: $book.title)
TextField("Author", text: $book.author)
}
Section("Progress") {
Stepper("Pages read: \(book.pagesRead) / \(book.totalPages)", value: $book.pagesRead, in: 0...book.totalPages)
ProgressView(value: book.progress)
.tint(book.isFinished ? .green : .blue)
Button(book.isFinished ? "Mark as unread" : "Mark as finished") {
withAnimation {
book.pagesRead = book.isFinished ? 0 : book.totalPages
}
}
}
}
.navigationTitle(book.title)
}
}
struct AddBookSheet: View {
@Environment(\.modelContext) private var context
@Environment(\.dismiss) private var dismiss
@State private var title = ""
@State private var author = ""
@State private var totalPages = 200
private var canSave: Bool {
!title.trimmingCharacters(in: .whitespaces).isEmpty && totalPages > 0
}
var body: some View {
NavigationStack {
Form {
TextField("Book title", text: $title)
TextField("Author", text: $author)
Stepper("Pages: \(totalPages)", value: $totalPages, in: 10...2000, step: 10)
}
.navigationTitle("Add Book")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button("Save") {
let book = ReadingBook(
title: title.trimmingCharacters(in: .whitespaces),
author: author.trimmingCharacters(in: .whitespaces),
totalPages: totalPages
)
context.insert(book)
dismiss()
}
.disabled(!canSave)
}
}
}
}
}
Drop those four Swift files into a fresh Xcode SwiftUI project, hit Command + R, and you have a complete native iOS and macOS app backed by SwiftData with live search, filtering, accessibility grouping, and instant persistence!
Debugging and common SwiftUI pitfalls
When SwiftUI confuses beginners, it is almost always one of five issues.
| Problem | Why it happens | Fast fix |
|---|---|---|
| ”The compiler is unable to type-check this expression in reasonable time” | One giant body with deeply nested views and modifiers | Split sections into small child struct views or computed var header: some View helpers |
@State keeps resetting unexpectedly | Parent changed the view’s identity (for example, id: UUID() generated inside body or switching if/else branches) | Store id on your model (let id = UUID()), never generate UUID() inside body |
| Modifier does not look right (padding, border, background) | Modifiers applied in the wrong order | Remember inside-out order: .padding() before .background() paints the padding too |
@Observable changes do not update a TextField | Missing @Bindable in child view | Mark the passed-in model parameter @Bindable var store: TaskStore |
| Preview crashes in Xcode | View reads @Environment(Store.self) or SwiftData without injecting them in #Preview | Pass .environment(TaskStore()) or .modelContainer(for: ..., inMemory: true) inside #Preview |
One more lifesaver for debugging unexpected re-renders: drop let _ = Self._printChanges() at the top of a view’s body temporarily. SwiftUI prints the exact property that caused body to run right into Xcode’s console.
Where to go from here
You now have every building block needed to design, wire up, persist, and ship real SwiftUI apps on iOS and macOS.
Start small. Pick one tiny app you would actually use yourself (a reading tracker, coffee log, or Pomodoro timer), keep your views small and composable, lean on @Observable and SwiftData, and run it on your real phone or Mac early.
If you want to strengthen your Swift fundamentals alongside SwiftUI, check out my free Swift Handbook and more tutorials.
Want me to talk about your product? You can sponsor this site.
Related posts about swift: