Bookmarks
ReferenceMobile developmentVerified

iOS and Swift

iOS and Swift — the Apple platform and language for iPhone and iPad apps. In this reference: SwiftUI, Xcode, concurrency, state, navigation, SwiftData and the App Store.

checked 1 Nov · next check 8 Nov · 58 min read

Sections
13
Reading
58 min
Current version
Swift 6.4; Xcode 27.2 (27B52); iOS 27.2
Written from
developer.apple.com/documentation

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What iOS and Swift are and how they work

Apps for iPhone and iPad are written in Swift — an Apple language where types are checked at build time, the absence of a value is expressed with optionals and memory is managed by the language itself. The interface is described declaratively in SwiftUI: what to show for the current data, and the framework updates the screen.

A native app in Swift and SwiftUI is the choice when the product lives on iPhone and iPad and has to get new system features straight away. Swift is written for servers too, but an iPhone app is built in Xcode — Apple’s development environment for the Mac, with an editor, device simulators in the Device Hub, a debugger and the Instruments profiler. If one team builds for iOS and Android at once, compare with the cross-platform route — it is covered in the Flutter reference, the section “What Flutter is and how it works”.

A SwiftUI app is a tree of types. A structure with the @main attribute implements the App protocol and lists scenes (Scene); the WindowGroup scene creates windows with a root view from which the view hierarchy grows. Data lives separately: a model with the @Observable macro holds the state, while a data layer — SwiftData, URLSession and the keychain — loads and saves it. When the data changes, SwiftUI itself updates the parts of the interface that depend on it.

Views do not store the app’s data: they describe the screen for the current state of the model.
swiftNotesApp.swift
import SwiftUI @Observablefinal class NoteStore {    var notes: [String] = ["Buy milk"]} @mainstruct NotesApp: App {    // the model is created once and lives as long as the app    @State private var store = NoteStore()     var body: some Scene {        WindowGroup {            ContentView()                .environment(store)        }    }} struct ContentView: View {    @Environment(NoteStore.self) private var store     var body: some View {        List(store.notes, id: \.self) { note in            Text(note)        }    }}

How SwiftUI differs from UIKit

FeatureSwiftUIUIKit
How the interface is describeddeclaratively: which views to show for this dataimperatively: view controller code creates the views and changes them
Who updates the screenthe framework, when the data changesthe code of the view controller
How to embed the othera UIKit view — via UIViewRepresentable and UIViewControllerRepresentablea SwiftUI screen — via UIHostingController

Choose SwiftUI for a new app: it does most of the work view controllers used to do. UIKit stays where it already exists and for components SwiftUI lacks; both frameworks work in one app, so nothing has to be rewritten all at once.

What to know beforehand

  • Programming basics: variables, functions, conditionals and loops. The language itself — in the section “Swift syntax”.
  • How HTTP requests and JSON work — the HTTP and REST reference.
  • Working with a code repository — the Git reference.

Section sources

the section is written from these pages

Cheat sheet

Swift syntax, SwiftUI views, state wrappers, concurrency and everyday Xcode actions; each line is explained in its own section.

Swift

TaskHow to write
Constant and variablelet name = "Ali", var count = 0
Declare the type explicitlylet price: Double = 70
Insert a value into a string"Total: \(count)"
A value that may be absentvar nickname: String? = nil
Unwrap an optionalif let nickname { … }
Exit early if there is no valueguard let nickname else { return }
Fallback valuenickname ?? "Guest"
Access through an optionaluser?.address?.city
Array and dictionary[1, 2, 3], ["en": "English"]
Iterate over the itemsfor item in items { … }
A case with an associated valueenum State { case failed(String) }
Your own data typestruct Point { var x = 0 }, class Counter { var count = 0 }
Shorthand closureitems.sorted { $0 > $1 }

SwiftUI

TaskHow to write
Vertical and horizontal stackVStack(alignment: .leading) { … }, HStack { … }
Layers on top of each otherZStack { … }
List from an arrayList(items) { item in Text(item.name) }
Repeat a view for each itemForEach(items) { item in … }
ButtonButton("Save") { save() }
Text fieldTextField("Name", text: $name)
Padding on all sides.padding()
Fixed size.frame(width: 40, height: 40)
Take up the free space in a stackSpacer()

State

TaskWrapper
Local value of a view@State private var isOn = false
Read and modify someone else’s @State@Binding var isOn: Bool, pass $isOn
A model that SwiftUI observes@Observable final class Store { … }
Own the model@State private var store = Store()
Pass the model down the hierarchy.environment(store), read with @Environment(Store.self)
Binding to a model field@Bindable var store, then $store.title

Concurrency

TaskHow to write
Asynchronous functionfunc load() async throws -> [Note]
Await the resultlet notes = try await load()
Start from ordinary codeTask { await refresh() }
Two loads in parallelasync let a = loadA(), async let b = loadB(), then await (a, b)
On the main actor only@MainActor func show() { … }
Load when the screen appears.task { await refresh() }
Your own actoractor Cache { … }

Xcode

TaskWhere
Choose a Simulator or an iPhonethe run destination menu in the toolbar
Build and runthe Run button or “Product → Run”
Stop the appthe Stop button in the toolbar
Connect an iPhone“Manage Devices” in the run destination menu, then Device Hub
Download a simulator runtimethe Get button next to the run destination, or “Xcode → Settings → Components”
See every build erroruntick “Stop build on first error” in “Xcode → Settings → General”
Rebuild everything from scratch“Product → Clean Build Folder”
Show the previewthe “Show Canvas” button; if the canvas is paused — Restart

Section sources

the section is written from these pages

Installation and first run

iOS development needs a Mac and Xcode: it includes the Swift compiler, the platform SDKs and simulators. Install Xcode from the Mac App Store, create a project from the App template and press Run — the app should open in the simulator.

What you need

  • A Mac with a version of macOS supported by the current Xcode. Each Xcode version requires its own minimum macOS — see the “SDKs and system requirements” table; the current version’s requirements are also listed in the “Versions and what’s new” section.
  • Xcode from the Mac App Store. Xcode betas are on the Apple Developer downloads page; earlier versions and other tools are downloaded from the same page after signing in with an Apple Account — Apple Developer Program membership is not required.
  • An Apple Account — to run the app on your own iPhone. TestFlight and the App Store require the Apple Developer Program; it is covered in the “Signing and publishing to the App Store” section.

If the iOS platform has not been downloaded yet, Xcode shows a Get button next to the “Any iOS Device” run destination; later, platforms and simulator runtimes are downloaded in “Xcode → Settings → Components”.

Swift itself does not depend on Xcode: on Linux and Windows the compiler is installed separately — installers are at swift.org/install.

New project

  1. In the “Welcome to Xcode” window, choose App in the “New Project” menu or “File → New → Project”. To choose the platform explicitly, click “Choose Template”, then the iOS platform and the App template.
  2. Enter the Product Name — this is the name the app will carry in the App Store and on the device after installation.
  3. Choose a team — the account Xcode signs the app with.
  4. Enter the Organization Identifier: from it and the product name Xcode assembles the Bundle Identifier (CFBundleIdentifier) — the app’s unique identifier in the system.
  5. Interface — SwiftUI, Language — Swift. Choose a folder and click Create.

First project

textproject tree
MyApp/├── MyApp.xcodeproj         project and target settings└── MyApp/    ├── MyAppApp.swift      entry point: @main and App    ├── ContentView.swift   root view    └── Assets.xcassets     icon, colours, images

Files are picked in the Project navigator on the left and edited in the editor. Target settings are in the project editor: the General tab holds the name, version and Bundle Identifier, the Signing & Capabilities tab — signing. The template already includes the #Preview macro: it shows the view on the canvas next to the code without running the app.

swiftContentView.swift
import SwiftUI struct ContentView: View {    @State private var taps = 0     var body: some View {        VStack(spacing: 16) {            Text("Taps: \(taps)")                .font(.largeTitle)            Button("Tap") {                taps += 1            }        }        .padding()    }} #Preview {    ContentView()}

Running in the simulator

Choose a simulator, for example an iPhone, in the run destination menu and press Run or “Product → Run”. Xcode builds and runs the app: Device Hub opens a compact window with the simulator screen, and the debug area appears at the bottom of the Xcode window. Stop the app with the Stop button. The simulator does not reproduce the performance or some of the hardware of a real device, so check the app on an iPhone before release.

Running on an iPhone

  1. Sign in to Xcode with an Apple Account: “Xcode → Settings → Apple Accounts”. Both a personal account and an Apple Developer Program account will work.
  2. In “Signing & Capabilities”, enable “Automatically manage signing”, choose a team and a unique Bundle Identifier. If the identifier is taken, Xcode shows a warning.
  3. Choose “Manage Devices” in the destination menu and connect the iPhone in Device Hub.
  4. On the iPhone, enable Developer Mode: “Settings → Privacy & Security → Developer Mode”. Confirm the restart in the warning; after the restart, confirm turning it on with your passcode.
  5. Choose the iPhone in the destination menu and press Run. On the first run, Xcode registers the device and creates a development provisioning profile.

Section sources

the section is written from these pages

Swift syntax

Swift is a compiled language with strict typing: the type of every constant and variable is known at build time, and the absence of a value is expressed only through an optional. To read the code of an iOS app, constants, optionals, collections, functions and closures, structures and classes, enumerations and error handling are enough.

Constants, variables and strings

swift
// let — the value is set oncelet appName = "Notes"var count = 0count += 1 // the type is inferred from the value; here it is stated explicitlylet price: Double = 70 // interpolation: an expression goes in \( )let summary = "\(appName): \(count)"let label = "Price: " + String(price) let text = """    First line    Second line    """

The type is inferred from the initial value: count is an Int, while price has its type stated explicitly, otherwise the literal 70 would give an Int. Values are never converted to another type implicitly, so a number is turned into a string with String(…) or interpolation. A multiline string is written in triple quotes; indentation matching the closing quotes is removed.

Optionals

An optional T? holds a value of type T or nil. A plain variable cannot be assigned nil — that is a compile-time error, so the type shows at once where a value may be missing.

swift
struct Address { var city: String }struct User {    var nickname: String?    var address: Address?} // Int(_:) returns an Int?: the string may not be a numberlet number = Int("42")if let number {    print("Number: \(number)")} func greet(_ name: String?) {    // early exit: below, name is no longer an optional    guard let name else { return }    print("Hello, \(name)")} let user: User? = User(nickname: nil, address: Address(city: "Tashkent"))let shownName = user?.nickname ?? "Guest"let city = user?.address?.city
NotationWhat it doesIf there is nil
if let x { … }unwraps the value inside the blockthe block is skipped
guard let x else { return }unwraps for the rest of the functionthe function exits
a ?? btakes the value or a fallbackthe result is b
a?.baccesses a property through the optionalthe result is nil
a!forces the unwrapa runtime error, the app crashes

Collections, loops and switch

swift
var tags = ["swift", "ios"]tags.append("xcode") var scores: [String: Int] = ["Ali": 3]scores["Malika"] = 5 // Set stores only unique valueslet cities: Set = ["Tashkent", "Samarkand", "Tashkent"]print(cities.count) for (name, score) in scores {    print("\(name): \(score)")} let score = scores["Malika"] ?? 0switch score {case 0:    print("no points")case let x where x > 10:    print("record: \(x)")default:    print("there are points")}

An array (Array) is ordered, a Set holds unique values without order, and a dictionary (Dictionary) holds key–value pairs, whose iteration order is arbitrary. A collection in let is immutable, in var it is mutable. switch matches against arbitrary patterns, including a where condition, and after a matching case it does not fall through to the next one, so no break is needed.

Functions and closures

swift
// the outside label is to, the inside name is name; _ removes the labelfunc send(_ text: String, to name: String, urgent: Bool = false) -> String {    let mark = urgent ? "Urgent! " : ""    return mark + text + ", \(name)!"}print(send("Hello", to: "Ali")) let numbers = [20, 19, 7, 12]let doubled = numbers.map { $0 * 2 }// a closure is the last argument, so it goes after the parentheseslet sorted = numbers.sorted { a, b in a > b }

A parameter has two parts: an argument label for the call site and a parameter name for the function body; _ calls the function without a label. A parameter can be given a default value (urgent: Bool = false) — such a parameter is omitted at the call site. A closure is a piece of code that can be passed around and called later; it sees the variables of the place where it was created. The last closure is written after the call parentheses (a trailing closure), and the parameters of short closures are named $0, $1.

Structures and classes

A structure (struct) is a value type: on assignment and when passed to a function it is copied. A class (class) is a reference type: the reference is copied, and both variables see one object.

swift
struct Point { var x = 0 }class Counter { var value = 0 } var p1 = Point()var p2 = p1p2.x = 10// 0: p2 has its own copyprint(p1.x) let c1 = Counter()let c2 = c1c2.value = 10// 10: c1 and c2 point to one objectprint(c1.value)
FeatureStructureClass
What is copiedthe whole valueonly the reference
Inheritancenoyes
Deinitializer deinitnoyes
Identity check ===noyes

Choose a structure by default: it is easier to reason about, and the Swift documentation advises making most of your own types structures and enumerations. Reach for a class when you need a shared mutable object, inheritance or object identity.

Enumerations, protocols and extensions

swift
enum LoadState {    case idle    case loaded([String])    case failed(String)} protocol Describable {    var summary: String { get }} // an extension adds protocol conformance to a typeextension LoadState: Describable {    var summary: String {        switch self {        case .idle:            return "Nothing loaded"        case let .loaded(items):            return "Loaded: \(items.count)"        case let .failed(message):            return "Error: \(message)"        }    }} let state = LoadState.loaded(["a", "b"])print(state.summary)

An enumeration case can have an associated value — its own for each instance, and switch takes it out with case let. A protocol describes requirements that classes, structures and enumerations conform to. An extension (extension) adds methods, computed properties and protocol conformance to an existing type — even a type from someone else’s library.

Errors: throws, try and do-catch

swift
enum NoteError: Error {    case empty    case tooLong(limit: Int)} // typed throws: only NoteError errorsfunc validate(_ text: String) throws(NoteError) {    guard !text.isEmpty else { throw .empty }    guard text.count <= 500 else { throw .tooLong(limit: 500) }} do {    try validate("")} catch NoteError.empty {    print("Empty note")} catch {    print("Error: \(error)")} // try? turns an error into nillet isValid = (try? validate("Buy bread")) != nil

A function with throws may throw an error — a value of any type that conforms to the Error protocol. Such a call is marked with try, and errors are caught in do-catch; without a pattern the catch receives the error in the constant error. The form throws(NoteError) is typed throws: the compiler checks that the function throws only that type. A plain throws throws any Error, and most code is written that way.

Section sources

the section is written from these pages

Concurrency: async/await and actors

Concurrency in Swift — asynchronous functions (async/await), tasks (Task) and actors that protect data from concurrent access. In the Swift 6 language mode the compiler checks data isolation, and most data races become errors as early as build time.

async and await

A function with async can pause in the middle and continue later. Every possible suspension point is marked with await, and between two such points the code runs without interference from other code. While a function waits for the network, the thread is free for other work — for the interface, for example.

swift
func rate(for code: String) async throws -> Double {    // instead of the network — a half-second pause    try await Task.sleep(for: .milliseconds(500))    return code == "USD" ? 12_000 : 13_500} func showRate() async {    do {        let usd = try await rate(for: "USD")        print("USD: \(usd)")    } catch {        print("Failed: \(error)")    }}

await is written only in asynchronous code: in the body of an async function or inside a task. From ordinary code, such as a button handler, start a task: Task { await showRate() }. Such a task inherits the actor isolation, the priority and the task-local values from where it was created.

In parallel: async let and task groups

swift
func loadRates() async throws -> (Double, Double) {    // both requests start at once, without waiting for each other    async let usd = rate(for: "USD")    async let eur = rate(for: "EUR")    return try await (usd, eur)} func loadAll(_ codes: [String]) async throws -> [String: Double] {    try await withThrowingTaskGroup(of: (String, Double).self) { group in        for code in codes {            group.addTask { (code, try await rate(for: code)) }        }        var result: [String: Double] = [:]        for try await (code, value) in group {            result[code] = value        }        return result    }}

async let creates a child task that runs in parallel with the surrounding code; the result is awaited with await when it is needed. A task group is needed when the number of tasks is known only at run time. Tasks form a hierarchy — this is structured concurrency: a parent does not finish before its child tasks, and its cancellation cancels them too.

Task cancellation

swift
let task = Task {    for code in ["USD", "EUR", "RUB"] {        // throws CancellationError if the task was cancelled        try Task.checkCancellation()        print(try await rate(for: code))    }}// later, for example when leaving the screentask.cancel()

Cancellation is cooperative: cancel() does not stop a task by force, it only marks it as cancelled. The task checks this itself: Task.checkCancellation() throws CancellationError, and Task.isCancelled lets you return a partial result.

Actors and the main actor

An actor is a reference type that lets only one task at a time into its mutable state. From the outside, the properties and methods of an actor are accessed through await: you may have to wait until the actor finishes other work. The main actor (MainActor) protects everything the interface shows; code with the @MainActor attribute runs on it. The View protocol in SwiftUI is marked @MainActor, so your views also run on the main actor.

Swift 6 checks crossing the isolation boundary at build time, not at run time.
swift
actor ImageCache {    private var images: [URL: Data] = [:]     func image(for url: URL) -> Data? {        images[url]    }     func store(_ data: Data, for url: URL) {        images[url] = data    }} @MainActorfinal class GalleryModel {    let cache = ImageCache()    var savedCount = 0     func save(_ data: Data, from url: URL) async {        // entering the actor’s isolation — only through await        await cache.store(data, for: url)        savedCount += 1    }}

Sendable: what can be passed

A type whose values can be passed between concurrency domains — tasks and actors — is called Sendable. It is a value type made of Sendable fields, a type without mutable state, or a type that protects its own state, such as a class with @MainActor. A structure that is not marked public and consists of Sendable fields becomes Sendable automatically; a class with mutable properties does not, and the Swift 6 compiler will not let you pass it to another actor.

swift
// Sendable automatically: a structure of Sendable fieldsstruct Rate {    let code: String    let value: Double} // not Sendable: mutable state with no protectionclass Draft {    var text = ""}

The Swift 6 mode and gradual migration

The Swift 6 language mode turns on full data-race checking. The mode is set per target, so a project is migrated gradually: first turn on the full checking as warnings in the Swift 5 mode, fix them, then switch the target to Swift 6.

What you needXcode settingIn the .xcconfig file
Data-race warnings in Swift 5 code“Strict Concurrency Checking” = “Complete”SWIFT_STRICT_CONCURRENCY = complete
Full checking, errors instead of warnings“Swift Language Version” = 6SWIFT_VERSION = 6

In a Swift Package Manager package, a manifest with swift-tools-version: 6.0 or newer enables mode 6 for all targets, and a lagging target can stay on Swift 5 with the .swiftLanguageMode(.v5) setting.

What Swift 6.2 and 6.4 added

  • With Swift 6.2 — default actor isolation (-default-isolation MainActor): unannotated code runs on the main actor, and there is no need to write @MainActor by hand. The mode is intended for interface code, scripts and executable targets.
  • With Swift 6.2 — the @concurrent attribute for a function that must run in parallel, outside the actor of the calling code.
  • With Swift 6.2 — an upcoming feature under which nonisolated async functions run in the context of the calling code, even on the main actor.
  • With Swift 6.4 — await inside defer: asynchronous clean-up runs before the function exits.
  • With Swift 6.4 — withTaskCancellationShield { … }: the code inside does not see task cancellation and carries its work through to the end.
swiftSwift 6.4
func upload(_ file: URL) async throws {    let handle = try FileHandle(forReadingFrom: file)    defer {        // close the file and report, even if the task was cancelled        await withTaskCancellationShield {            try? handle.close()            await reportFinished(file)        }    }    try await send(handle)}

In SwiftUI: the .task modifier

The .task modifier starts an asynchronous task before the view appears, and the task lives as long as the view: if SwiftUI removes the view from the screen or the view’s identity changes, the task is cancelled. The default priority is userInitiated.

swift
import SwiftUI struct RateView: View {    @State private var usd: Double?     var body: some View {        Text(usd.map { "USD: \($0)" } ?? "Loading…")            .task {                // cancels itself if the screen is dismissed first                usd = try? await rate(for: "USD")            }    }}

Section sources

the section is written from these pages

SwiftUI: views and modifiers

A view in SwiftUI is a structure that implements the View protocol and describes what to display in its body property. SwiftUI calls body itself whenever the data changes and redraws only the affected parts of the screen, so views are lightweight and are created anew many times.

swiftGreetingView.swift
import SwiftUI struct GreetingView: View {    let name: String    let newNotes: Int     var body: some View {        VStack {            Text("Hello, \(name)")                .font(.title)            Text("New notes: \(newNotes)")                .foregroundStyle(.secondary)        }    }}

The type of body is declared as some View: the compiler infers the exact type from its contents. A complex screen is assembled from small views, both built-in ones such as Text, Image and VStack, and your own. Inputs are plain properties of the structure. SwiftUI can recreate a view at any moment, so no heavy work is done in its initialiser.

Modifiers and their order

A modifier is a method of a view that returns a new view wrapped around the original one. Modifiers are chained, and each one wraps the result of the previous one — from the outside, not the inside — so the order changes the result.

swift
// frame around the full 200 pt widthText("Title")    .frame(width: 200)    .border(Color.gray) // frame around the text onlyText("Title")    .border(Color.gray)    .frame(width: 200)

A container modifier applies to child views unless they have set their own value: .font(.body) on a VStack changes the font of all texts inside, except those where a different font is specified. Some modifiers exist only for a single type: bold() on Text is applied before general modifiers such as .padding(), because those no longer return a Text.

Lists: List and ForEach

swift
struct Note: Identifiable {    let id = UUID()    var title: String} struct NotesList: View {    let notes: [Note]     var body: some View {        List {            Section("Notes") {                ForEach(notes) { note in                    Text(note.title)                }            }        }    }}

List is a vertical list that scrolls by itself when it does not fit on the screen. Rows are defined as separate views or with ForEach over a collection, and these approaches can be mixed. Items must be distinguishable: the type implements Identifiable with an id property, or an id: key is passed to ForEach. List modifiers add a swipe on a row (swipeActions) and pull-to-refresh (refreshable).

Controls

ControlWhat it doesExample
Buttonperforms an actionButton("Save") { save() }
TextFieldedits text on a single lineTextField("Name", text: $name)
Toggleswitches between “on” and “off”Toggle("Notifications", isOn: $isOn)
Pickerselects one of several optionsPicker("Theme", selection: $theme) { ... }
Sliderselects a value from a rangeSlider(value: $volume, in: 0...1)
Stepperincrements and decrements a valueStepper("Servings: \(count)", value: $count)

A control receives its value through a binding — $isOn, $theme; where it comes from is covered in the section “State and data flow”. How to make an interface work with VoiceOver and large text is covered in the “Accessibility (a11y)” reference.

When a view is redrawn

In SwiftUI the interface is a function of the data. A user action changes the state, SwiftUI calls body again on the views that depend on the changed data, compares the new description with the previous one and redraws only the affected parts. The screen is never updated by hand.

  1. The user taps a button or types text.
  2. The handler changes the value of @State or an @Observable model property.
  3. SwiftUI calls body again on the views that depend on this value.
  4. SwiftUI compares the new description with the previous one to find the changed parts.
  5. Only what has changed is updated on screen.

The .id(_:) modifier ties the identity of a view to a value: if the value changes, SwiftUI treats the view as a new one. And equatable() keeps a child view from being updated when its new value equals the old one.

Lifecycle: onAppear and task

ModifierWhen it runs
.onAppear { … }before the view appears on screen
.onDisappear { … }after the view has disappeared
.task { … }an asynchronous task before the view appears
.task(id: value) { … }before the view appears and on every change of value

The phase of the whole scene — active, inactive or in the background — is read from the environment through @Environment(\.scenePhase); this is covered in the section “State and data flow”. How to embed an existing UIKit view through UIViewRepresentable is covered in the section “What iOS and Swift are and how they work”.

Section sources

the section is written from these pages

Layout: stacks, grids and scrolling

Layout in SwiftUI is assembled from containers: stacks arrange elements in a line, grids arrange them in rows and columns, ScrollView scrolls. Sizing is resolved top down: the parent offers a size, the child answers with its own, and the parent places it — so exact coordinates are almost never needed.

How SwiftUI works out sizes

SwiftUI walks the hierarchy recursively: the parent offers its child views a size, each answers with the size it needs, and once every one has answered, the parent draws them. Built-in views behave in different ways:

  • Take up all the space they are offered: Color, Circle, LinearGradient.
  • Take their ideal size from the content: Text and containers.
  • Have a constant ideal size: Toggle, DatePicker.

The .frame modifier wraps a view in a new invisible view of the given size; after that the negotiation goes on as before, only inside that frame.

Stacks, alignment and Spacer

swifta feed row
HStack(alignment: .top, spacing: 12) {    Circle()        .fill(.orange)        .frame(width: 40, height: 40)    VStack(alignment: .leading, spacing: 4) {        Text("Malika")            .font(.headline)        Text("A new note about Swift")            .foregroundStyle(.secondary)    }    Spacer()}.padding(.horizontal)
ContainerHow it arranges elementsThe alignment parameter
HStackin a rowvertically: .top, .center, .bottom
VStackin a columnhorizontally: .leading, .center, .trailing
ZStackone on top of anotheralong both axes: .topLeading, .bottom and others

By default, stacks centre their content and put a small gap between elements; spacing sets it explicitly. alignment aligns the elements inside the stack, not the stack itself in its parent. Spacer stretches along the stack’s main axis and pushes its neighbours to the edges, while Divider draws a separator and takes up no extra space.

padding, frame and the safe area

ModifierWhat it does
.padding()the system padding on all sides
.padding(.horizontal, 16)padding on the given sides only
.frame(width: 40, height: 40)a fixed size
.frame(maxWidth: .infinity)stretch across the full available width
.fixedSize()keep the ideal size, do not compress
.ignoresSafeArea()extend into the safe area, for example for a background
.safeAreaInset(edge: .bottom) { … }show a panel at the edge, moving the safe area in

Grids and scrolling

swifta spec table
Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 8) {    GridRow {        Text("Memory")        Text("256 GB")    }    GridRow {        Text("Screen")        Text("6.3 inches")    }}

Grid lays out the rows of GridRow into columns: the widest cell sets the column width, and the tallest one sets the row height. It creates all the child views up front, so it aligns cells well. For a long, scrolling grid there are the lazy LazyVGrid and LazyHGrid: they create cells only when those are needed on the screen.

swifta product catalogue
ScrollView {    LazyVGrid(columns: [GridItem(.adaptive(minimum: 150))]) {        ForEach(1...60, id: \.self) { number in            Text("Item \(number)")                .frame(maxWidth: .infinity, minHeight: 80)                .background(.thinMaterial)        }    }    .padding()}

Switch to a lazy grid only if profiling has shown that a plain Grid opens slowly: a lazy grid aligns its cells less well.

Adaptivity: ViewThatFits

swift
ViewThatFits(in: .horizontal) {    HStack {        Label("Call", systemImage: "phone")        Label("Message", systemImage: "message")    }    VStack {        Label("Call", systemImage: "phone")        Label("Message", systemImage: "message")    }}

ViewThatFits goes through the alternatives in the given order and shows the first one that fits in the proposed size; in: .horizontal checks the width only. That way one and the same row of buttons stands in a row on iPad and in a column on a narrow iPhone. The size class tells how much horizontal room a view has: .compact for a phone in portrait orientation, .regular on iPad — it is read from the environment (horizontalSizeClass) and the layout is switched on it; built-in views, navigation for one, change their appearance by themselves. Different columns for iPad and iPhone are set by navigation — that is covered in the section “Navigation between screens”.

Worked example: a product card

swiftProductCard.swift
struct ProductCard: View {    let name: String    let price: String    let inStock: Bool     var body: some View {        VStack(alignment: .leading, spacing: 8) {            ZStack(alignment: .topTrailing) {                Color.gray.opacity(0.2)                    .frame(height: 140)                if !inStock {                    Text("Out of stock")                        .font(.caption)                        .padding(6)                        .background(.red)                        .foregroundStyle(.white)                }            }            Text(name)                .font(.headline)                .lineLimit(2)            HStack {                Text(price)                    .fontWeight(.bold)                Spacer()                Button("Add to basket") { }                    .disabled(!inStock)            }        }        .padding()    }}
  • VStack(alignment: .leading) stacks the picture, the name and the price in a column aligned to the left edge.
  • ZStack(alignment: .topTrailing) puts the “Out of stock” label on top of the picture in the top right corner.
  • Color takes the whole width the stack offered, and .frame(height: 140) fixes the height only.
  • Spacer in the bottom HStack presses the price to the left and the button to the right.

Section sources

the section is written from these pages

State and data flow

State is data the interface depends on. Each value has a single source of truth: @State stores a value inside a view, a model with the @Observable macro holds screen or app data, and @Binding, @Bindable and @Environment provide access to it without copies.

@State and @Binding

swift
import SwiftUI struct ProductView: View {    @State private var isFavorite = false     var body: some View {        VStack {            Text(isFavorite ? "In favourites" : "Not in favourites")            FavoriteButton(isFavorite: $isFavorite)        }    }} struct FavoriteButton: View {    @Binding var isFavorite: Bool     var body: some View {        Button(isFavorite ? "Remove" : "Add to favourites") {            isFavorite.toggle()        }    }}

@State is the source of truth for a value owned by the view itself; SwiftUI stores it, and the value survives the structure being recreated. Declare it private and use it only for data of this view and its children. $isFavorite produces a binding, and @Binding in a child view reads and changes someone else’s state without copying it. Since Xcode 27, @State is implemented by the State() macro.

The @Observable model

swiftNotesModel.swift
import SwiftUI @Observablefinal class NotesModel {    var notes: [String] = []    var filter = ""     var visible: [String] {        filter.isEmpty ? notes : notes.filter { $0.contains(filter) }    }     func add(_ text: String) {        notes.append(text)    }     func save() {        // write to disk or send to the server    }}

The @Observable macro adds change tracking to a class at build time. A view depends on the model when its body reads one of the model’s properties, and updates only when a property it has read changes; changes to the other properties leave it untouched. Collections and computed properties such as visible are tracked as well. Don’t declare the Observable protocol alone without the macro — conforming to the protocol by itself adds no tracking.

Create the model in one place and store it in @State — in the App, a scene or the root screen. Pass it down as a parameter or through the environment, and change its fields through @Bindable bindings.

One model for the whole app: views get a reference to it, not a copy.
swift
@mainstruct NotesApp: App {    @State private var model = NotesModel()     var body: some Scene {        WindowGroup {            NotesScreen()                .environment(model)        }    }} struct NotesScreen: View {    @Environment(NotesModel.self) private var model     var body: some View {        // bindings to the model’s fields from the environment        @Bindable var model = model        List {            TextField("Search", text: $model.filter)            ForEach(model.visible, id: \.self) { note in                Text(note)            }        }    }}

@Bindable: bindings to model fields

You can change model properties directly, for example in a button action: model.add("…"). A binding is needed when a control requires one: TextField, Toggle. @Bindable creates $ bindings for the mutable properties of an @Observable model — on a view parameter, on a local variable in body or on a model from the environment.

swift
@Observablefinal class Note {    var title = ""    var isPinned = false} struct NoteEditor: View {    @Bindable var note: Note     var body: some View {        VStack {            TextField("Title", text: $note.title)            Toggle("Pin", isOn: $note.isPinned)        }        .padding()    }}

Environment: @Environment

The environment passes data to all descendants without parameters in every intermediate view. A model is put into it with the .environment(model) modifier and read by type: @Environment(NotesModel.self). If there is no such object in the environment, SwiftUI throws an exception and the app crashes; declaring NotesModel? returns nil instead of crashing. The environment also holds system values, for example \.dismiss to close the current screen and \.scenePhase for the scene phase.

swift
struct RootView: View {    @Environment(\.scenePhase) private var scenePhase    @Environment(NotesModel.self) private var model     var body: some View {        NotesScreen()            .onChange(of: scenePhase) {                // the app moved to the background and may terminate soon                if scenePhase == .background {                    model.save()                }            }    }}

The phase is .active — the scene is on screen and receives touches, .inactive — on screen, but its work should be paused, and .background — the scene is not visible. In an App, the value is aggregated across all scenes at once. A custom environment value is declared with an EnvironmentKey and an extension of EnvironmentValues.

Which wrapper to choose

WrapperWho owns the dataWhen to use
@Statethe view itselfa screen’s local value — a flag, text, the selected item; ownership of an @Observable model
@Bindingthe parentthe child view needs to read and change someone else’s @State
@Observablewhoever created the objectscreen or app data together with the logic
@Bindableowns nothing$ bindings to a model’s fields are needed
@Environmentan ancestor in the hierarchymany views need the model or a setting

Migrating from ObservableObject

Before iOS 17, models were written with the ObservableObject protocol and properties were marked with @Published. Observation tracks optionals and collections of objects, works with plain @State and @Environment, and updates a view only when a property it has read changes. Migration can be gradual, one model at a time: @StateObject and @EnvironmentObject also work with @Observable models.

BeforeAfter
class Library: ObservableObject@Observable class Library
@Published var booksvar books
@StateObject private var library@State private var library
.environmentObject(library).environment(library)
@EnvironmentObject var library: Library@Environment(Library.self) private var library
@ObservedObject var book: Bookvar book: Book

A property that does not need to be tracked is marked with the @ObservationIgnored macro.

Section sources

the section is written from these pages

Data: networking, SwiftData and the keychain

An app’s data usually lives in three places: on the network — URLSession fetches it; on the device — in the SwiftData database and UserDefaults settings; and in the keychain — for passwords and tokens. JSON is turned into Swift types through Codable, and networking works asynchronously via async/await.

Making a network request

swiftRatesAPI.swift
import Foundation struct Rate: Decodable {    let code: String    let value: Double} enum APIError: Error {    case notHTTP    case badStatus(Int)} func loadRates() async throws -> [Rate] {    let url = URL(string: "https://api.example.com/rates")!    let (data, response) = try await URLSession.shared.data(from: url)    guard let http = response as? HTTPURLResponse else {        throw APIError.notHTTP    }    // success — only 2xx codes    guard (200...299).contains(http.statusCode) else {        throw APIError.badStatus(http.statusCode)    }    return try JSONDecoder().decode([Rate].self, from: data)}

For simple requests, the shared session URLSession.shared is enough; you create your own session when you need custom configuration or a delegate. data(from:) waits for the transfer to complete and returns the data and the response. There are two kinds of failure: a transfer failure — data(from:) throws an error — and a server response with an error code, which you check via statusCode. What the HTTP codes and methods mean is covered in the HTTP and REST reference, section “Response codes”.

URLSession connections go through App Transport Security (ATS): it requires HTTPS, so an http:// address will not load without extra configuration. Exceptions are declared with the NSAppTransportSecurity key in Info.plist; how to debug an ATS rejection is covered in the section “Common errors and diagnostics”.

JSON and Codable

swift
struct Article: Codable {    let id: Int    let title: String    let authorName: String?     // JSON key names differ from the property names    enum CodingKeys: String, CodingKey {        case id        case title = "headline"        case authorName = "author_name"    }} let json = #"{"id": 1, "headline": "Swift", "author_name": null}"#let article = try JSONDecoder().decode(Article.self, from: Data(json.utf8))

Codable combines Encodable and Decodable. If every property of the type is itself encodable — String, Int, Double, Date, URL, and arrays, dictionaries and optionals of them — the conformance is synthesised automatically. If you only need to read a response, Decodable is enough. The CodingKeys enumeration maps different key names; a property missing from CodingKeys needs a default value.

SwiftData: a database on the device

swiftItemsApp.swift
import SwiftDataimport SwiftUI @Modelfinal class Item {    var title: String    var createdAt: Date     init(title: String, createdAt: Date = .now) {        self.title = title        self.createdAt = createdAt    }} @mainstruct ItemsApp: App {    var body: some Scene {        WindowGroup {            ItemsList()        }        .modelContainer(for: Item.self)    }}
swiftItemsList.swift
struct ItemsList: View {    @Environment(\.modelContext) private var context    @Query(sort: \Item.createdAt, order: .reverse)    private var items: [Item]     var body: some View {        List {            ForEach(items) { item in                Text(item.title)            }            .onDelete { offsets in                for index in offsets {                    context.delete(items[index])                }            }        }        .toolbar {            Button("Add") {                context.insert(Item(title: "New item"))            }        }    }}
  • @Model makes a class persistable and adds change tracking to it, like @Observable.
  • .modelContainer(for:) at the top of the hierarchy sets up the store for the models you list.
  • The model context (modelContext) from the environment inserts and deletes objects; it saves changes on its own, and you can write them out right away by calling save().
  • @Query loads objects with sorting and refreshes the view whenever the data changes.

Settings: UserDefaults

swift
let defaults = UserDefaults.standarddefaults.set(true, forKey: "showsHints")let showsHints = defaults.bool(forKey: "showsHints")

UserDefaults stores an app’s small settings as key–value pairs: numbers, strings, dates, URL, and arrays and dictionaries of them. A value is updated in memory straight away and written to disk asynchronously; it is included in the device’s backup but is not synchronised between devices. In SwiftUI, the @AppStorage property wrapper exposes the same store: @AppStorage("showsHints") var showsHints = true takes the value from UserDefaults and refreshes the view when it changes.

Section sources

the section is written from these pages

Signing and publishing on the App Store

To distribute an app to testers through TestFlight or release it on the App Store, you need to be enrolled in the Apple Developer Program. From there the path is always the same: an archive in Xcode, an upload to App Store Connect, testing in TestFlight, App Review and publication.

A free account and the Apple Developer Program

CapabilityApple Account without the programmeApple Developer Program
Running on your own device from Xcodeyes, with a personal team (Personal Team)yes
Limitsup to 3 devices and up to 3 apps per device; profiles and the App ID are valid for 7 daysprofiles are managed in Certificates, Identifiers & Profiles
App Store Connect, TestFlight, App Storenoyes
Costfree$99 per year

After 7 days, an app installed with a personal team stops launching: it has to be rebuilt and installed again. For organisations that distribute apps only to their own employees there is the Apple Developer Enterprise Program — $299 per year.

Code signing

Signing confirms that the app was released by your account. Xcode signs it for you: in “Signing & Capabilities”, turn on “Automatically manage signing” and select a team from the Apple Developer Program. Signing certificates live in the cloud as cloud-managed certificates and are tied to the account; when you upload or export a build, Xcode creates the required signing assets itself. Manual signing requires your own signing certificates.

What to check before the first upload

  • The bundle ID must be unique and written in reverse domain notation: com.example.notes. After the first upload to App Store Connect it cannot be changed.
  • The version number (CFBundleShortVersionString) is visible on the App Store; the build number (CFBundleVersion) tells builds of the same version apart. Both are required; Xcode can increment the build number itself during upload.
  • The app icon: an Icon Composer file or an asset catalog.
  • A usage description in Info.plist for each protected resource: location, camera, microphone, contacts and calendar. The system shows this text in the permission prompt.
  • All the project’s targets are assigned to a team from the Apple Developer Program.

Archive and upload

  1. Choose a scheme and a run destination, then “Product → Archive”. An archive is a build with debugging information; it will appear in the Organizer window (“Window → Organizer”).
  2. Select the archive and click Validate App: Xcode will check whether the build is ready for upload.
  3. Click Distribute App and choose “TestFlight & App Store”: Xcode will sign the build, increment the build number and upload it together with the symbols for crash reports.
  4. If the app is being uploaded for the first time, Xcode will ask for the details and create the app record in App Store Connect.

TestFlight

TestFlight distributes beta versions to internal testers from your team and to external testers — up to 10,000 people, by email or a public link. The “TestFlight Internal Only” option limits the build to your team, and such a build cannot be submitted to the App Store. Builds for TestFlight must follow the App Review Guidelines, major changes to a beta version go through TestFlight App Review, and builds must not be distributed for any compensation.

App Review: common reasons for rejection

  • Crashes and errors: test the app on a device before submitting.
  • An unfinished version: placeholder text, empty websites and temporary content.
  • No access to features: if the app has a sign-in, provide a working demo account or a demo mode and keep the server running during the review.
  • No link to a privacy policy in App Store Connect or inside the app.
  • The privacy details are not filled in: in App Store Connect you declare what data the app collects — Apple publishes the answers on the app’s page.
  • An account can be created but not deleted inside the app.
  • The description and screenshots do not match the app; screenshots must show the app in use, not just a splash screen or a sign-in screen.

The review status is visible in App Store Connect. The release option is chosen at submission: manually, automatically once approved, or no earlier than a set date; after release, the app appears in the selected countries within 24 hours. The current App Store requirement is a build made with Xcode 26 or later and the iOS 26 SDK or later (from 28 April 2026); the table of requirements is in the section “Versions and what’s new”.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the Issue navigator and the build log: the red line with the error text opens the place in the code, and the full log is in the Report navigator. Read a build error in full: Swift 6 concurrency errors carry note: hints with possible fixes under the message. Reproduce a crash with the debugger and breakpoints, and analyse a user-side crash from the crash report.

static property '…' is not concurrency-safe because it is nonisolated global shared mutable state

Cause: a mutable global or static variable is reachable from any concurrency domain at once, and the compiler cannot rule out a data race. static let shared gets the same message when the object’s type is not Sendable.

swiftdon’t do this
struct Settings {    // mutable static property without isolation    static var retries = 3}
swiftdo this instead
struct Settings {    // the value never changes — make it a constant    static let retries = 3} final class Analytics {    // the shared object is not Sendable — isolate it to the main actor    @MainActor static let shared = Analytics()}

nonisolated(unsafe) turns the check off for a variable. Use it only when every access to it is already guarded by a lock or a queue.

sending '…' risks causing data races

Cause: a value without Sendable cannot be passed to another isolation domain, for example into a function with @MainActor. A common case is a public structure with Sendable fields: the compiler grants implicit Sendable conformance only to internal types; for a public type the author has to declare it, because Sendable is part of the public API contract.

swiftdo this instead
public struct ColorComponents: Sendable {    public let red: Float    public let green: Float    public let blue: Float}

Declare Sendable only when the type is genuinely safe for concurrent use: removing the conformance later is a breaking API change.

call to actor-isolated instance method '…' in a synchronous nonisolated context

Cause: synchronous code without isolation calls an actor method. A common case is deinit: it is always nonisolated, even on an actor and on a class with @MainActor. If the work in deinit does not have to be synchronous, add a Task { … } and pass the values it needs into it — but not self, not even implicitly.

main actor-isolated instance method '…' cannot be used to satisfy nonisolated protocol requirement

Cause: in a protocol without explicit isolation a requirement counts as nonisolated — it is called from any concurrency domain, so the implementation must not touch actor state. If the requirement is always called on the main actor, mark the whole protocol or the individual requirement with @MainActor; if the implementation does not touch actor state, mark it nonisolated.

main actor-isolated default value in a nonisolated context

Cause: a default value or a static property of a nonisolated type creates an object with @MainActor. If the initialiser does not need main actor state, mark it nonisolated init: isolated properties remain accessible only on the main actor.

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure.

Cause: the app requests an http:// address, or a server that does not meet the ATS requirements: TLS 1.2 or newer, a trusted certificate and forward secrecy ciphers.

  • Move the address to https:// — URLSession negotiates the most secure connection the server supports.
  • If an HTTPS server refuses the connection, fix its TLS and certificate.
  • An exception under the NSAppTransportSecurity key is a last resort: it weakens protection, and App Store requires justification for some exceptions.

The app crashes when launched from Xcode

The cause is visible where the debugger stops. A stop on main or in AppDelegate is usually an Objective-C exception or a runtime problem with a message like Thread 8: EXC_BAD_INSTRUCTION (code=…). A Fatal error message is an unhandled Swift error. Set a breakpoint before the crash site, check the variable values and step through the code.

textdebugger console
(lldb) v notes(lldb) po model.visible

v prints a variable quickly, while po compiles and evaluates the expression and works slower. To see values without stopping, add a Debugger Command action with v to the breakpoint and turn on “Automatically continue after evaluating actions” — then there is no need to clutter the code with print calls.

A crash in a user’s build from TestFlight or the App Store

The cause is unknown, and a debugger cannot attach to such a build: distribution builds lack the debugging entitlement. Analyse the crash from the report:

  1. Build the app with symbols and keep the Xcode archive before distribution.
  2. Get the crash report — from Xcode Organizer or from the device.
  3. Symbolicate the report: addresses turn into function names and line numbers.
  4. Compare the report with common crash patterns, fix the code and add a test so the crash does not happen again.

Signing errors on a device

Xcode names the cause in the signing error itself. With automatic signing, turn on “Automatically manage signing” and pick a team in “Signing & Capabilities” — Xcode registers the device and creates the signing assets itself. With manual signing: a certificate cannot be used for signing without its private key, and before a certificate is deleted from the keychain it is revoked in the developer account. The setup steps are in the section “Installation and first run”; managing certificates manually is covered in Apple’s article “Synchronizing code signing identities with your developer account”.

Minor issues

SymptomCauseWhat to do
Memory grows and is never releaseda strong reference cycle or forgotten objectswatch the Memory gauge, open the Debug Memory Graph and find the strong references
The processor is busy while the app idleswork never stopsopen the CPU gauge in the Debug navigator and click it for details
The layout breaks only in dark mode or with large textthe interface was not checked in these modesenable environment overrides and open the view hierarchy debugger
The app is terminated when memory runs lowthe system frees memory and terminates the appopen the jetsam event report — it shows the memory state — and reduce memory use
The preview (#Preview) fails to buildthe error is visible only in the canvas logclick “Diagnostics” in the corner of the preview canvas and read the message
Logs from the device are neededprint output is invisible in a distribution buildlog messages through the os framework and view them in the Console app on the Mac
The screen does not update after data changesSwiftUI does not track the valuecheck @State and @Observable — the section “State and data flow”
The app cannot be launched on an iPhoneDeveloper Mode is off or signing is not set upthe steps are in the section “Installation and first run”

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Swift 6.4, Xcode 27 and iOS 27. The latest Xcode release is 27.2, from 29 October 2026; the latest iOS release is 27.2, from 26 October 2026. Major Xcode and iOS releases come once a year in autumn, and Swift releases are announced in posts on swift.org; Apple keeps the App Store requirements for Xcode and the SDK on the Upcoming Requirements page.

ProductVersionDateRequirements
Swift6.415 September 2026included in Xcode 27
Xcode27.2 (27B52)29 October 2026macOS Tahoe 26.6 or later, a Mac with Apple silicon; debugging on devices with iOS 17 or later
Xcode27.1 (27A9275)15 October 2026the same
iOS and iPadOS27.226 October 2026the iOS 27 SDK is included in Xcode 27
iOS 1818.7.1126 October 2026an update for devices running iOS 18
App Store requirementEffective from
Built in Xcode 26 or later with the iOS 26 SDK or later28 April 2026
Deployment target — iOS 13 or later9 September 2026

What changed in Swift 6.4

  • Concurrency: await can now be written inside defer, and withTaskCancellationShield protects cleanup from task cancellation.
  • State and data flow: @Observable types have gained fine-grained and continuous change notifications.
  • Swift syntax: an optional some or any type is written without parentheses — some Shape? instead of (some Shape)?; the @diagnose attribute controls warnings right in code.
  • Swift syntax: the module selector :: says which module to take an API from when the same name is declared in two modules.
  • Installation and first run: Swift Package Manager builds through Swift Build by default — the same on Linux, macOS and Windows.
  • Common errors and diagnostics: LLDB finds Swift modules by exact dependencies, and dSYM bundles have become noticeably smaller.

What changed in Xcode 27 and iOS 27

  • Installation and first run: Xcode 27 installs and runs only on Macs with Apple silicon. Simulators and devices are gathered in Device Hub, and an iPhone with iOS 27 can be connected over the network, with no cable.
  • Installation and first run: code inside #Preview runs on the main actor, and #Preview(arguments:) shows a grid of previews for a set of arguments.
  • State and data flow: when building with Xcode 27, @State is implemented as a macro and the initial expression is no longer evaluated on every re-creation of the view; this also works on iOS 17. If a @State property has an initial value in its declaration, assigning to it in init no longer compiles — remove the value from the declaration.
  • Navigation between views: when building with the iOS 27 SDK, TabView requires the selected tab to be visible, otherwise the app may crash.
  • Data: AsyncImage caches images according to HTTP caching headers.
  • Common errors and diagnostics: the LLDB command language swift task tree prints the tree of Swift tasks.

Deprecated and removed

  • PreviewProvider and its modifiers are deprecated in Xcode 27 — use #Preview.
  • The .roundedBorder and .squareBorder field styles are deprecated without a compiler warning (soft deprecated) — use .bordered.
  • FileDocument is deprecated — use ReadableDocument for reading, or Document for reading and writing.
  • For new models use the @Observable macro rather than the ObservableObject protocol — the section “State and data flow” describes how to migrate.
  • A UIKit app built with the iOS 27 SDK must use the scene-based life cycle, otherwise it will not launch; and it must include a launch screen: Info.plist needs one of the keys UILaunchScreen, UILaunchScreens, UILaunchStoryboardName or UILaunchStoryboards.
  • canOpenURL: is deprecated: open the URL straight away and handle the failure; universal links remove the need for such a check altogether.

How to upgrade

  1. Update macOS to Tahoe 26.6 or later and install Xcode 27; Xcode 27 does not run on Macs with Intel processors.
  2. Build the project with the iOS 27 SDK and go through the warnings: the @State and TabView changes show up exactly in such a build.
  3. Replace PreviewProvider with #Preview and the deprecated field styles with .bordered.
  4. Move the target to the Swift 6 language mode: the section “Concurrency: async/await and actors” walks through it step by step.
  5. Check the App Store requirements: builds from Xcode 26 or later with the iOS 26 SDK, minimum version iOS 13 or later.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “iOS and Swift” topic
All references · 61