Swift and SwiftUI
The code is right when it compiles with zero warnings in Swift 6 language
mode and the app does what the story says. For how it should look, call the
Skill tool with mac-design. For copyable view code, read
../../design/mac-design/patterns.md.
Concurrency
The template sets main-actor default isolation: every type and function runs
on the main actor unless you say otherwise. UI code needs no annotations.
| Work |
Put it in |
| UI state, views, view models |
Default (main actor) |
| CPU-heavy pure work (parsing, image work, diffing) |
A nonisolated function marked @concurrent |
| Shared mutable state used off the main thread |
An actor |
| A C callback (event tap, Carbon hotkey, CoreAudio listener) |
A nonisolated static func that hops back with Task { @MainActor in ... } |
- Data that crosses actors is
Sendable: structs and enums of Sendable
values, or final class with only let properties.
MainActor.assumeIsolated { } inside a callback you know runs on the main
thread (a main run loop Timer, a main queue notification).
Task { } inherits the actor. Task.detached only when it must not.
- Fix a concurrency error at its type, not with
@unchecked Sendable or
nonisolated(unsafe). Those two are a last resort, with a comment why.
- Runtime trap the compiler misses. A closure created inside a
@MainActor type and passed to an API without a @Sendable closure
parameter (DispatchSource.setEventHandler, DispatchWorkItem,
addPeriodicTimeObserver, CoreAudio listener blocks) inherits the main
actor. When it runs on a background queue, Swift 6 crashes the app. Write
it as { @Sendable in ... }, and run every background path once after
any concurrency change.
State
@Observable classes for models. @State in the view that owns one,
@Bindable to bind to its properties, .environment(model) to share it.
@ObservationIgnored on caches, timers, and handles, so they never
trigger a redraw.
@State for view-local values. @AppStorage for small preferences.
Keychain for secrets.
ForEach(items) over values, never ForEach($items) for data the user
can delete: a row can read an index that no longer exists and crash. Get
a binding by looking the item up by id.
SwiftData
@Model classes, .modelContainer on the scene, @Query in views,
@Environment(\.modelContext) to insert and delete.
- Every new property has a default value, so existing stores still open.
- Store at
~/Library/Application Support/<AppName>/. Allow an override
(APP_STORE) so tests never touch the real data.
- Give every model its own
uid: UUID. persistentModelID changes on the
first save, so it breaks selection and lookups.
- Undo: register the reverse of each action on the window's undo manager.
SwiftData's automatic undo is not reliable. Code in
../../design/mac-design/patterns.md (Undo with SwiftData).
- Need SQL, a CLI, or several processes on one file? Use SQLite with WAL
through a small library target instead.
Menu commands
SwiftUI Commands do not observe @Observable models, so a title or a
.disabled(...) that reads the model goes stale. In testing, neither
@FocusedValue (from .focusedSceneValue) nor an @ObservedObject inside
the commands updated reliably: the menu stayed disabled with a row
selected. What works: mirror the selection into a small ObservableObject,
observe it in the App, and pass the values into the commands. The App's
body then rebuilds the menus when they change.
@MainActor final class MenuState: ObservableObject {
static let shared = MenuState()
@Published private(set) var selection: Set<UUID> = []
func update(_ s: Set<UUID>) { if selection != s { selection = s } }
}
// AppModel: var selection: Set<UUID> = [] { didSet { MenuState.shared.update(selection) } }
struct MyApp: App {
@ObservedObject private var menu = MenuState.shared
var body: some Scene {
Window("App", id: "main") { ContentView() }
.commands { AppCommands(model: model, selectedIDs: menu.selection) }
}
}
Disable items with .disabled(selectedIDs.isEmpty) and resolve the target
again when the item fires. Never ship items that stay enabled and do
nothing. Check the menu from outside the app (test-mac-app skill, "Menu
check").
A menu shortcut also fires while a text field has focus. Never use Delete,
Command-Delete, arrows, or Return as menu shortcuts. Handle them on the
list with .onDeleteCommand and .onKeyPress.
Names Swift already uses
Never name a type Task, View, Color, Image, Text, Section,
Label, Menu, Group, or Settings. Task breaks every Task { }.
Use Todo, TaskItem, NoteSection.
AppKit bridges
SwiftUI covers windows, lists, and forms. AppKit is still the answer for:
- Floating panels that do not steal focus:
NSPanel with
.nonactivatingPanel hosting a SwiftUI view (NSHostingView, with
sizingOptions = [] for a fixed frame).
- Text views with custom behavior:
NSViewRepresentable around NSTextView.
- Status items with custom click handling:
NSStatusItem.
- Key and mouse monitors:
NSEvent.addLocalMonitorForEvents. Remove the
monitor when the view goes away.
For system hooks (hotkeys, Accessibility, screen capture), call the Skill
tool with os-integrations.
Compiler errors
| Error |
Fix |
cannot find 'X' in scope right after adding a file |
swift package clean --scratch-path ~/Library/Developer/<AppName>/build |
Main actor-isolated ... from a nonisolated context |
Make the caller main-actor, or await the call |
Sending 'x' risks causing data races |
Make the type Sendable, or keep it on one actor |
The compiler is unable to type-check this expression |
Split the view into smaller subviews or let constants |
ambiguous use of 'Task' |
A type in your code is named Task; rename it |
Fix the first error first. Later errors often come from it.
Swift 6 errors
Moving an existing Swift 5 app? Read
../../ship/build-and-verify/existing-app.md
first: expect several build rounds, then hunt the runtime trap above.
| Error |
Fix |
Static let of a non-Sendable type (formatter, NSFont, CFString) |
@MainActor on the enclosing type, a computed var, or a commented nonisolated(unsafe) |
sending 'note' risks causing data races in a main-queue observer |
Copy the Sendable parts (an id, a pid) out of the notification before MainActor.assumeIsolated |
| Observer token captured before it is assigned |
Keep the token in a small @MainActor class |
| "pattern that the region-based isolation checker does not understand" in a task group |
Use an array of Task { @MainActor in ... } and await each one |
Vars changed from OperationQueue blocks under NSLock |
OSAllocatedUnfairLock(initialState:) |
@objc action on an NSMenuItem subclass |
@MainActor @objc func |
Done when the app builds with zero warnings in Swift 6 language mode and
the story's acceptance checks pass.
1---2name: swift-swiftui3description: Swift 6 and SwiftUI code rules for macOS apps, including concurrency, state, SwiftData, AppKit bridges, and fixes for common compiler errors. Use when writing, reviewing, or debugging Swift code in a Mac app, or on concurrency, Sendable, or "not in scope" errors.4metadata:5 source: https://skillmd.com/skills/tuyv/swift-swiftui6---78# Swift and SwiftUI910The code is right when it compiles with zero warnings in Swift 6 language11mode and the app does what the story says. For how it should look, call the12Skill tool with `mac-design`. For copyable view code, read13[../../design/mac-design/patterns.md](../../design/mac-design/patterns.md).1415## Concurrency1617The template sets main-actor default isolation: every type and function runs18on the main actor unless you say otherwise. UI code needs no annotations.1920| Work | Put it in |21| --- | --- |22| UI state, views, view models | Default (main actor) |23| CPU-heavy pure work (parsing, image work, diffing) | A `nonisolated` function marked `@concurrent` |24| Shared mutable state used off the main thread | An `actor` |25| A C callback (event tap, Carbon hotkey, CoreAudio listener) | A `nonisolated` static func that hops back with `Task { @MainActor in ... }` |2627- Data that crosses actors is `Sendable`: structs and enums of `Sendable`28 values, or `final class` with only `let` properties.29- `MainActor.assumeIsolated { }` inside a callback you know runs on the main30 thread (a main run loop `Timer`, a main queue notification).31- `Task { }` inherits the actor. `Task.detached` only when it must not.32- Fix a concurrency error at its type, not with `@unchecked Sendable` or33 `nonisolated(unsafe)`. Those two are a last resort, with a comment why.34- **Runtime trap the compiler misses.** A closure created inside a35 `@MainActor` type and passed to an API without a `@Sendable` closure36 parameter (`DispatchSource.setEventHandler`, `DispatchWorkItem`,37 `addPeriodicTimeObserver`, CoreAudio listener blocks) inherits the main38 actor. When it runs on a background queue, Swift 6 crashes the app. Write39 it as `{ @Sendable in ... }`, and run every background path once after40 any concurrency change.4142## State4344- `@Observable` classes for models. `@State` in the view that owns one,45 `@Bindable` to bind to its properties, `.environment(model)` to share it.46- `@ObservationIgnored` on caches, timers, and handles, so they never47 trigger a redraw.48- `@State` for view-local values. `@AppStorage` for small preferences.49 Keychain for secrets.50- `ForEach(items)` over values, never `ForEach($items)` for data the user51 can delete: a row can read an index that no longer exists and crash. Get52 a binding by looking the item up by id.5354## SwiftData5556- `@Model` classes, `.modelContainer` on the scene, `@Query` in views,57 `@Environment(\.modelContext)` to insert and delete.58- Every new property has a default value, so existing stores still open.59- Store at `~/Library/Application Support/<AppName>/`. Allow an override60 (`APP_STORE`) so tests never touch the real data.61- Give every model its own `uid: UUID`. `persistentModelID` changes on the62 first save, so it breaks selection and lookups.63- Undo: register the reverse of each action on the window's undo manager.64 SwiftData's automatic undo is not reliable. Code in65 [../../design/mac-design/patterns.md](../../design/mac-design/patterns.md) (Undo with SwiftData).66- Need SQL, a CLI, or several processes on one file? Use SQLite with WAL67 through a small library target instead.6869## Menu commands7071SwiftUI `Commands` do not observe `@Observable` models, so a title or a72`.disabled(...)` that reads the model goes stale. In testing, neither73`@FocusedValue` (from `.focusedSceneValue`) nor an `@ObservedObject` inside74the commands updated reliably: the menu stayed disabled with a row75selected. What works: mirror the selection into a small `ObservableObject`,76observe it in the `App`, and pass the values into the commands. The App's77body then rebuilds the menus when they change.7879```swift80@MainActor final class MenuState: ObservableObject {81 static let shared = MenuState()82 @Published private(set) var selection: Set<UUID> = []83 func update(_ s: Set<UUID>) { if selection != s { selection = s } }84}85// AppModel: var selection: Set<UUID> = [] { didSet { MenuState.shared.update(selection) } }8687struct MyApp: App {88 @ObservedObject private var menu = MenuState.shared89 var body: some Scene {90 Window("App", id: "main") { ContentView() }91 .commands { AppCommands(model: model, selectedIDs: menu.selection) }92 }93}94```9596Disable items with `.disabled(selectedIDs.isEmpty)` and resolve the target97again when the item fires. Never ship items that stay enabled and do98nothing. Check the menu from outside the app (`test-mac-app` skill, "Menu99check").100101A menu shortcut also fires while a text field has focus. Never use Delete,102Command-Delete, arrows, or Return as menu shortcuts. Handle them on the103list with `.onDeleteCommand` and `.onKeyPress`.104105## Names Swift already uses106107Never name a type `Task`, `View`, `Color`, `Image`, `Text`, `Section`,108`Label`, `Menu`, `Group`, or `Settings`. `Task` breaks every `Task { }`.109Use `Todo`, `TaskItem`, `NoteSection`.110111## AppKit bridges112113SwiftUI covers windows, lists, and forms. AppKit is still the answer for:114115- Floating panels that do not steal focus: `NSPanel` with116 `.nonactivatingPanel` hosting a SwiftUI view (`NSHostingView`, with117 `sizingOptions = []` for a fixed frame).118- Text views with custom behavior: `NSViewRepresentable` around `NSTextView`.119- Status items with custom click handling: `NSStatusItem`.120- Key and mouse monitors: `NSEvent.addLocalMonitorForEvents`. Remove the121 monitor when the view goes away.122123For system hooks (hotkeys, Accessibility, screen capture), call the Skill124tool with `os-integrations`.125126## Compiler errors127128| Error | Fix |129| --- | --- |130| `cannot find 'X' in scope` right after adding a file | `swift package clean --scratch-path ~/Library/Developer/<AppName>/build` |131| `Main actor-isolated ... from a nonisolated context` | Make the caller main-actor, or `await` the call |132| `Sending 'x' risks causing data races` | Make the type `Sendable`, or keep it on one actor |133| `The compiler is unable to type-check this expression` | Split the view into smaller subviews or `let` constants |134| `ambiguous use of 'Task'` | A type in your code is named `Task`; rename it |135136Fix the first error first. Later errors often come from it.137138## Swift 6 errors139140Moving an existing Swift 5 app? Read141[../../ship/build-and-verify/existing-app.md](../../ship/build-and-verify/existing-app.md)142first: expect several build rounds, then hunt the runtime trap above.143144| Error | Fix |145| --- | --- |146| Static `let` of a non-Sendable type (formatter, `NSFont`, `CFString`) | `@MainActor` on the enclosing type, a computed `var`, or a commented `nonisolated(unsafe)` |147| `sending 'note' risks causing data races` in a main-queue observer | Copy the Sendable parts (an id, a pid) out of the notification before `MainActor.assumeIsolated` |148| Observer token captured before it is assigned | Keep the token in a small `@MainActor` class |149| "pattern that the region-based isolation checker does not understand" in a task group | Use an array of `Task { @MainActor in ... }` and await each one |150| Vars changed from `OperationQueue` blocks under `NSLock` | `OSAllocatedUnfairLock(initialState:)` |151| `@objc` action on an `NSMenuItem` subclass | `@MainActor @objc func` |152153Done when the app builds with zero warnings in Swift 6 language mode and154the story's acceptance checks pass.