Native foundations

SwiftUI explained

Build a SwiftUI foundation with views, state ownership, Observation, value-based navigation and adaptable layouts.

Apirex TeamUpdated
On this page
  1. What SwiftUI is
  2. Views and modifiers
  3. State
  4. Navigation
  5. Layouts
  6. Frequently asked questions

What SwiftUI is

SwiftUI is Apple’s declarative framework for building interfaces in Swift. You describe views for the current state, and SwiftUI manages updates when data those views depend on changes.

A view is not a screenshot or a permanent widget object that you locate and edit manually. It describes content, layout and behavior. When a form changes, update its data and let the view describe the new result instead of synchronizing several labels by hand.

SwiftUI is not a database, authentication service or payment backend. An app still needs clear data ownership, asynchronous work and failure handling. Begin with local examples so you understand view updates before introducing server requests, permissions and persistent records.

Create an iOS App project in Xcode with SwiftUI as its interface. Keep the generated App entry point and use each example view as its root content, or call it from ContentView. Use an iOS 17 or later deployment target to run every example unchanged because the Observation example needs it.

As of November 2026, Apple documents different minimum versions for different SwiftUI APIs. SwiftUI began with iOS 13, but NavigationStack and Grid need iOS 16, and SwiftUI’s Observation support needs iOS 17. A current Xcode installation does not make every API available on every supported phone.

Compile one example before adding the next. If an availability error appears, check the deployment target and API documentation instead of removing the annotation. For a production app supporting earlier systems, choose an alternative implementation or add a deliberate availability check where appropriate.

Views and modifiers

A SwiftUI view conforms to View and supplies a body describing its content. Modifiers return modified views, letting you add typography, spacing, colors and behavior through an ordered chain.

swift
import SwiftUI

struct GreetingView: View {
    let name: String

    var body: some View {
        Text("Hello, \(name)")
            .font(.title2)
            .padding()
            .background(.blue.opacity(0.12))
            .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}

Use GreetingView(name: "Ada") in the generated app’s root view. Its immutable input allows reuse without creating a separate state owner for the name. The some View return type lets Swift preserve the concrete structure without requiring you to spell out the full nested type produced by the modifiers.

Modifier order changes the result because each operation wraps what came before it. Here, the tinted background includes the padding, and the rounded shape clips that result. Placing the background before padding would leave the outer spacing unpainted; reason through the chain when spacing looks unexpected.

Prefer semantic text styles such as title2 over fixed font sizes unless there is a clear requirement otherwise. Allow controls to respond to available space and text scaling. A balanced default layout may still clip at larger accessibility sizes, so test those settings before polishing visual details.

Keep expensive sorting, file reads and network work outside body. SwiftUI may evaluate it repeatedly, so an innocent-looking calculation can become repeated work. Prepare display data elsewhere and use lifecycle-aware asynchronous patterns when needed rather than starting another request every time the view is evaluated.

Xcode previews let you inspect an isolated view without navigating through the entire app. The #Preview macro was introduced with Xcode 15; use a current Xcode and compatible preview destination. This development-time declaration does not add a preview screen to the shipped application.

swift
#Preview {
    GreetingView(name: "Ada")
        .padding()
}
// Run the actual app to test its complete user journey.

A preview helps verify spacing and labels, but it cannot establish that production authentication, permissions or persistence works. Supply representative sample content, then run the app in Simulator and on a device where relevant. Treat a successful preview as feedback about one view, not acceptance of an entire feature.

State

Use @State for data owned by a view and @Binding when a child needs to edit an existing value owned elsewhere. For shared reference models, the Observation framework’s @Observable macro integrates with SwiftUI on iOS 17 and later.

swift
import SwiftUI

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 12) {
            Text("Count: \(count)")
            Button("Add one") { count += 1 }
        }
        .padding()
    }
}

Count belongs to CounterView, and changing it updates the displayed number. SwiftUI manages storage according to view identity rather than making each new view value a completely independent persistent counter. State is not durable storage: removing the view or restarting the app may require a separate persistence strategy.

A binding is a two-way connection to existing storage, not another independent copy. Use the dollar-sign projection of the state property when passing its binding. This child edits the parent’s Boolean, keeping one source of truth while separating the toggle’s interface from ownership.

swift
import SwiftUI

struct SettingsView: View {
    @State private var remindersEnabled = false

    var body: some View {
        ReminderToggle(isEnabled: $remindersEnabled)
            .padding()
    }
}

struct ReminderToggle: View {
    @Binding var isEnabled: Bool

    var body: some View {
        Toggle("Reminders", isOn: $isEnabled)
    }
}

The toggle only changes local UI state; it does not request notification permission or schedule anything. Keep example scope clear so a working switch is not mistaken for a complete reminder feature. A real implementation should separately model authorization, scheduling outcomes and understandable recovery when permission is denied.

For a reference model, import Observation and annotate the class with @Observable. In this iOS 17+ example the owning view retains its model instance in @State. SwiftUI tracks reads of observable properties used by body and can update dependent content when those properties change.

swift
import SwiftUI
import Observation

@Observable
final class CounterModel {
    var count = 0

    func increment() {
        count += 1
    }
}

struct ModelCounterView: View {
    @State private var model = CounterModel()

    var body: some View {
        VStack(spacing: 12) {
            Text("Count: \(model.count)")
            Button("Add one") { model.increment() }
        }
        .padding()
    }
}

Observation does not make data persistent or automatically resolve concurrency concerns. When adding asynchronous work, keep UI-facing mutation on the appropriate actor and design ownership explicitly. If a child needs bindings into an observable model, @Bindable is the related tool; a plain @Binding remains suitable for the Boolean child above.

For deployment targets below iOS 17, the older ObservableObject approach remains relevant rather than simply removing @Observable. Follow a coherent observation and ownership approach for each feature. Mixing property wrappers without understanding their responsibilities makes unexpected resets and stale values harder to diagnose.

Navigation

NavigationStack provides stack-based navigation on iOS 16 and later. NavigationLink(value:) carries a route value, while navigationDestination maps that value’s type to the view displayed by the stack.

swift
import SwiftUI

struct Topic: Hashable, Identifiable {
    let id: Int
    let title: String
}

struct TopicsView: View {
    private let topics = [
        Topic(id: 1, title: "Views"),
        Topic(id: 2, title: "State")
    ]

    var body: some View {
        NavigationStack {
            List(topics) { topic in
                NavigationLink(topic.title, value: topic)
            }
            .navigationTitle("Topics")
            .navigationDestination(for: Topic.self) { topic in
                Text(topic.title)
                    .navigationTitle(topic.title)
            }
        }
    }
}

Run TopicsView() as the root content. Its Hashable values identify selected topics, and the destination modifier supplies the detail for that type. Attach destination mappings where the stack can see them, not inside a lazily created list row whose existence depends on scrolling.

For larger applications, routes should express navigation intent rather than contain an entire mutable database record. A stable record identifier is often a better long-lived route than a snapshot of every field. The destination can then load current data and show an understandable missing-record state if that record was deleted.

Use ordinary platform back behavior unless a requirement justifies custom navigation. Test opening a detail, returning, changing data and reopening it. If deep links or restoration are later required, represent and validate route state explicitly instead of assuming the visible screen alone contains enough information.

Layouts

VStack arranges children vertically, HStack horizontally and ZStack in overlapping layers. LazyVStack creates content as needed inside a scrolling container, while Grid aligns content across rows and columns.

The basic stacks are available from iOS 13, LazyVStack from iOS 14, and Grid from iOS 16. This example therefore needs iOS 16 or later. Grid is not LazyVGrid: use the eager container for a small aligned summary rather than assuming every two-dimensional layout should create a huge dataset at once.

swift
import SwiftUI

struct LayoutDemo: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                HStack {
                    Text("Progress").font(.headline)
                    Spacer()
                    Text("Today")
                }
                ZStack {
                    RoundedRectangle(cornerRadius: 12)
                        .fill(.blue.opacity(0.12))
                    Text("Keep going").padding()
                }
                Grid(alignment: .leading) {
                    GridRow { Text("Read"); Text("10 minutes") }
                    GridRow { Text("Walk"); Text("20 minutes") }
                }
                LazyVStack(alignment: .leading) {
                    ForEach(1...50, id: \.self) { number in
                        Text("Entry \(number)")
                    }
                }
            }
            .padding()
        }
    }
}

The fixed integer range has unique stable values, making each value a suitable identity here. Editable records should use persistent IDs instead of current indexes. Stable identity lets SwiftUI associate updates and local state with the correct item when a collection is inserted into, deleted from or reordered.

Do not solve every layout issue with fixed widths and heights. Start with alignment, flexible containers and spacing, then check narrow screens and larger text. Lazy containers reduce unnecessary off-screen creation, but they do not make heavy image decoding or repeated calculations free; profile a slow screen before guessing at its bottleneck.

Apirex generates Swift/SwiftUI projects you can open in Xcode and Kotlin/Compose projects you can open in Android Studio. Apple and Android versions are separate projects. Review state ownership and navigation as you would in hand-written code, then test complete journeys with real input instead of treating a working preview as acceptance.

Try the binding example with the same value displayed in a parent Text label as well as the child toggle. Both should respond to a single edit because they read the same storage. If they disagree, look for an accidental second state property rather than adding manual synchronization between views.

When experimenting with the observable model, temporarily add a reset method and invoke it from a second button. Keep both actions on the same model instance. Creating a new model inside body for each evaluation would undermine the ownership demonstrated by the example and make changes appear to vanish unexpectedly.

For a useful learning sequence, run the greeting, counter, settings, topics and layout examples separately before combining them. Then build one small journey that edits a value, navigates to a summary and returns. Verify that the data remains where its intended owner lives, and decide explicitly whether it must survive an app restart.

Frequently asked questions

Is SwiftUI the same as Swift?

No. Swift is the language, while SwiftUI is an interface framework. Swift also supports non-UI work such as models and networking.

How do @State and @Binding differ?

State marks storage owned by the view. A binding lets another view read and write existing storage without owning a separate copy.

Which examples require iOS 17?

The @Observable example requires SwiftUI’s iOS 17 Observation support. NavigationStack and Grid require iOS 16; the simpler state examples have earlier availability.

Do previews replace Simulator testing?

No. Previews help inspect isolated views. Run the app to verify navigation, services, permissions and persistent data.

Can SwiftUI coexist with UIKit?

Yes. Apple provides interoperability mechanisms for using them together, so adoption need not replace every existing screen at once.

All guides

Build it on your own computer

Describe the app and Apirex writes real source you own, then builds it on your machine.

AndroidKotlin · Jetpack ComposeReal source on your computer

Opens Apirex with this prompt. Pick the Android · Kotlin tab before you send. The Free plan includes 5 Rex Credits a day.