SyntaxStudy
Sign Up
Swift Beginner 1 min read

SwiftUI Basics

SwiftUI is Apple's declarative UI framework, introduced in 2019. Views are defined as structs conforming to the View protocol with a computed body property that returns the UI hierarchy. State management uses property wrappers: @State for local view state, @Binding for two-way data flow to child views, @ObservedObject for external observable objects, and @StateObject for owning an observable object. SwiftUI automatically re-renders affected views when state changes — you describe what the UI should look like for a given state, not how to transition between states.
Example
import SwiftUI

// Basic view
struct ContentView: View {
    @State private var count = 0
    @State private var name = ""

    var body: some View {
        VStack(spacing: 20) {
            Text("Count: \(count)")
                .font(.largeTitle)
                .foregroundColor(count > 0 ? .green : .primary)

            HStack {
                Button("−") { count -= 1 }
                    .buttonStyle(.bordered)
                Button("+") { count += 1 }
                    .buttonStyle(.borderedProminent)
            }

            TextField("Enter name", text: $name)
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal)

            if !name.isEmpty {
                Text("Hello, \(name)!")
                    .transition(.slide)
            }
        }
        .padding()
        .animation(.default, value: name)
    }
}

// List view
struct TodoItem: Identifiable {
    let id = UUID()
    var title: String
    var isDone: Bool
}

struct TodoListView: View {
    @State private var items = [
        TodoItem(title: "Learn SwiftUI", isDone: true),
        TodoItem(title: "Build an app", isDone: false),
    ]

    var body: some View {
        List($items) { $item in
            HStack {
                Image(systemName: item.isDone ? "checkmark.circle.fill" : "circle")
                    .foregroundColor(item.isDone ? .green : .gray)
                Text(item.title)
                    .strikethrough(item.isDone)
            }
            .onTapGesture { item.isDone.toggle() }
        }
        .navigationTitle("Todo List")
    }
}