Design & media

swift-macos

Try it

Build native macOS apps with Swift 6.3, SwiftUI, SwiftData, concurrency, and on-device AI.

What it does

Reference material for macOS app development on Swift 6.3 / Xcode 26.6, targeting macOS 14+ through macOS 26 Tahoe. Covers SwiftUI scenes (WindowGroup, Settings, MenuBarExtra), menus and commands, native Table, and macOS-specific modifiers. SwiftData section shows @Model, @Query, #Predicate, FetchDescriptor, relationships, VersionedSchema migration, and CloudKit sync. Concurrency covers MainActor default isolation, @concurrent, actors, TaskGroup, Sendable, and AsyncSequence. Foundation Models shows ~3B-parameter on-device LLM calls with @Generable structured output. Swift Testing examples include parameterized tests and in-memory ModelContainer setup. ScreenCaptureKit covers screen, app aud…

When to use it

  • Building a native Mac app with windows, menus, MenuBarExtra, and SwiftData persistence
  • Adding on-device AI features with Foundation Models and structured output
  • Configuring Developer ID signing and notarytool notarization for distribution
  • Capturing screen content or app audio with ScreenCaptureKit

The skill document

macOS App Development - Swift 6.3

Build native macOS apps with Swift 6.3 (latest: 6.3.3, bundled in Xcode 26.6, Jun 2026), SwiftUI, SwiftData, and macOS 26 Tahoe (26.6 current). Target macOS 14+ for SwiftData/@Observable, macOS 15+ for latest SwiftUI, macOS 26 for Liquid Glass and Foundation Models. Note Xcode 26.6 still bundles the macOS 26.5 SDK, so 26.6-only API is not yet buildable. For the WWDC 2026 beta stack (macOS 27, Xcode 27, Swift 6.4, shipping fall 2026), see references/fall-2026-releases.md.

Quick Start

import SwiftUI
import SwiftData

@Model
final class Project {
    var name: String
    var createdAt: Date
    // Named ProjectTask, not Task - `Task` would shadow `Swift.Task`
    @Relationship(deleteRule: .cascade) var tasks: [ProjectTask] = []

    init(name: String) {
        self.name = name
        self.createdAt = .now
    }
}

@Model
final class ProjectTask {
    var title: String
    var isComplete: Bool
    var project: Project?

    init(title: String) {
        self.title = title
        self.isComplete = false
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup("Projects") {
            ContentView()
        }
        .modelContainer(for: [Project.self, ProjectTask.self])
        .defaultSize(width: 900, height: 600)

        #if os(macOS)
        Settings { SettingsView() }

        MenuBarExtra("Status", systemImage: "circle.fill") {
            MenuBarView()
        }
        .menuBarExtraStyle(.window)
        #endif
    }
}

struct ContentView: View {
    @Query(sort: \Project.createdAt, order: .reverse)
    private var projects: [Project]

    @Environment(\.modelContext) private var context
    @State private var selected: Project?

    var body: some View {
        NavigationSplitView {
            List(projects, selection: $selected) { project in
                NavigationLink(value: project) {
                    Text(project.name)
                }
            }
            .navigationSplitViewColumnWidth(min: 200, ideal: 250)
        } detail: {
            if let selected {
                DetailView(project: selected)
            } else {
                ContentUnavailableView("Select a Project",
                    systemImage: "sidebar.left")
            }
        }
    }
}

Scenes & Windows

ScenePurpose
WindowGroupResizable windows (multiple instances)
WindowSingle-instance utility window
SettingsPreferences (Cmd+,)
MenuBarExtraMenu bar with .menu or .window style
DocumentGroupDocument-based apps

Open windows: @Environment(\.openWindow) var openWindow; openWindow(id: "about")

For complete scene lifecycle, see references/app-lifecycle.md.

.commands {
    CommandGroup(replacing: .newItem) {
        Button("New Project") { /* ... */ }
            .keyboardShortcut("n", modifiers: .command)
    }
    CommandMenu("Tools") {
        Button("Run Analysis") { /* ... */ }
            .keyboardShortcut("r", modifiers: [.command, .shift])
    }
}

Table (macOS-native)

Table(items, selection: $selectedIDs, sortOrder: $sortOrder) {
    TableColumn("Name", value: \.name)
    TableColumn("Date") { Text($0.date, format: .dateTime) }
        .width(min: 100, ideal: 150)
}
.contextMenu(forSelectionType: Item.ID.self) { ids in
    Button("Delete", role: .destructive) { delete(ids) }
}

For forms, popovers, sheets, inspector, and macOS modifiers, see references/swiftui-macos.md.

@Observable

@Observable
final class AppState {
    var projects: [Project] = []
    var isLoading = false

    func load() async throws {
        isLoading = true
        defer { isLoading = false }
        projects = try await ProjectService.fetchAll()
    }
}

// Use: @State var state = AppState()          (owner)
// Pass: .environment(state)                    (inject)
// Read: @Environment(AppState.self) var state  (child)

SwiftData

@Query & #Predicate

@Query(filter: #Predicate { !$0.isArchived }, sort: \Project.name)
private var active: [Project]

// Dynamic predicate
func search(_ term: String) -> Predicate {
    #Predicate { $0.name.localizedStandardContains(term) }
}

// FetchDescriptor (outside views)
var desc = FetchDescriptor(predicate: #Predicate { $0.isArchived })
desc.fetchLimit = 50
let results = try context.fetch(desc)
let count = try context.fetchCount(desc)

Relationships

@Model final class Author {
    var name: String
    @Relationship(deleteRule: .cascade, inverse: \Book.author)
    var books: [Book] = []
}

@Model final class Book {
    var title: String
    var author: Author?
    @Relationship var tags: [Tag] = []  // many-to-many
}

Delete rules: .cascade, .nullify (default), .deny, .noAction.

Schema Migration

enum SchemaV1: VersionedSchema { /* ... */ }
enum SchemaV2: VersionedSchema { /* ... */ }

enum MigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] }
    static var stages: [MigrationStage] {
        [.lightweight(fromVersion: SchemaV1.self, toVersion: SchemaV2.self)]
    }
}

// Apply: .modelContainer(for: Model.self, migrationPlan: MigrationPlan.self)

CloudKit Sync

Enable iCloud capability, then .modelContainer(for: Model.self) auto-syncs. Constraints: all properties need defaults/optional, no unique constraints, optional relationships.

For model attributes, background contexts, batch ops, undo/redo, and testing, see SwiftData references below.

Concurrency (Swift 6.2+)

Default MainActor Isolation

Opt entire module into main actor - all code runs on main actor by default:

// Package.swift
.executableTarget(name: "MyApp", swiftSettings: [
    .defaultIsolation(MainActor.self),
])

Or Xcode: Build Settings > Swift Compiler > Default Isolation > MainActor.

@concurrent

Mark functions for background execution:

@concurrent
func processFile(_ url: URL) async throws -> Data {
    let data = try Data(contentsOf: url)
    return try compress(data) // runs off main actor
}
// After await, automatically back on main actor
let result = try await processFile(fileURL)

Use for CPU-intensive work, I/O, anything not touching UI.

Actors

actor DocumentStore {
    private var docs: [UUID: Document] = [:]
    func add(_ doc: Document) { docs[doc.id] = doc }
    func get(_ id: UUID) -> Document? { docs[id] }
    nonisolated let name: String
}
// Requires await: let doc = await store.get(id)

Structured Concurrency

// Parallel with async let
func loadDashboard() async throws -> Dashboard {
    async let profile = fetchProfile()
    async let stats = fetchStats()
    return try await Dashboard(profile: profile, stats: stats)
}

// Dynamic with TaskGroup
func processImages(_ urls: [URL]) async throws -> [NSImage] {
    try await withThrowingTaskGroup(of: (Int, NSImage).self) { group in
        for (i, url) in urls.enumerated() {
            group.addTask { (i, try await loadImage(url)) }
        }
        var results = [(Int, NSImage)]()
        for try await r in group { results.append(r) }
        return results.sorted { $0.0 < $1.0 }.map(\.1)
    }
}

Sendable

struct Point: Sendable { var x, y: Double }              // value types: implicit
final class Config: Sendable { let apiURL: URL }          // final + immutable
actor SharedState { var count = 0 }                       // mutable: use actors
// Enable strict mode: .swiftLanguageMode(.v6) in Package.swift

AsyncSequence & Observations

// Stream @Observable changes (macOS 26+ / iOS 26+, SE-0475)
// Observations uses a closure init, not Observations(of:).
let progresses = Observations { manager.progress }
for await p in progresses { print(p) }

// Typed NotificationCenter (macOS 26+)
struct DocSaved: NotificationCenter.MainActorMessage {
    typealias Subject = Document
    static var name: Notification.Name { .init("DocSaved") }
    let id: UUID
}
NotificationCenter.default.post(DocSaved(id: document.id), subject: document)
let token = NotificationCenter.default.addObserver(of: document, for: DocSaved.self) { msg in
    refresh(msg.id)
}

For concurrency deep dives, see concurrency references below.

Foundation Models (macOS 26+)

On-device ~3B LLM. Free, offline, private:

import FoundationModels

let session = LanguageModelSession()
let response = try await session.respond(to: "Summarize: \(text)")
print(response.content)  // respond() returns Response, not Content

// Structured output
@Generable struct Summary { var title: String; var points: [String] }
let result = try await session.respond(to: prompt, generating: Summary.self)
let summary: Summary = result.content

For tool calling, streaming, and sessions, see references/foundation-models.md.

Testing

import Testing

@Suite("Project Tests")
struct ProjectTests {
    @Test("creates with defaults")
    func create() {
        let p = Project(name: "Test")
        #expect(p.name == "Test")
    }

    @Test("formats sizes", arguments: [(1024, "1 KB"), (0, "0 KB")])
    func format(bytes: Int, expected: String) {
        #expect(formatSize(bytes) == expected)
    }
}

// SwiftData testing
let container = try ModelContainer(
    for: Project.self,
    configurations: ModelConfiguration(isStoredInMemoryOnly: true)
)
let ctx = ModelContext(container)
ctx.insert(Project(name: "Test"))
try ctx.save()

For exit tests, attachments, UI testing, see references/testing.md.

Distribution

MethodSandboxNotarizationReview
App StoreRequiredAutomaticYes
Developer IDRecommendedRequiredNo
Ad-HocNoNoLocal only
xcodebuild archive -scheme MyApp -archivePath MyApp.xcarchive
xcodebuild -exportArchive -archivePath MyApp.xcarchive \
  -exportPath ./export -exportOptionsPlist ExportOptions.plist
xcrun notarytool submit ./export/MyApp.dmg \
  --apple-id you@example.com --team-id TEAM_ID \
  --password @keychain:AC_PASSWORD --wait
xcrun stapler staple ./export/MyApp.dmg

For complete distribution guide, see references/distribution.md.

SPM

// swift-tools-version: 6.3
let package = Package(
    name: "MyApp",
    platforms: [.macOS(.v14)],
    targets: [
        .executableTarget(name: "MyApp", swiftSettings: [
            .swiftLanguageMode(.v6),
            .defaultIsolation(MainActor.self),
        ]),
        .testTarget(name: "MyAppTests", dependencies: ["MyApp"]),
    ]
)

For build plugins, macros, and Swift Build, see references/spm-build.md.

Liquid Glass (macOS 26)

Apps rebuilt with Xcode 26 SDK get automatic Liquid Glass styling. Use .glassEffect() for custom glass surfaces, GlassEffectContainer for custom hierarchies. Opt out (Xcode 26 only): UIDesignRequiresCompatibility = YES in Info.plist keeps the legacy visual style - a temporary migration aid. Apps rebuilt with Xcode 27 (beta) can no longer opt out; the key is ignored and Liquid Glass is mandatory (see references/fall-2026-releases.md).

ScreenCaptureKit

Capture screen content, app audio, and microphone (macOS 12.3+):

import ScreenCaptureKit

let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
guard let display = content.displays.first else { return }

// Filter: specific apps only
let filter = SCContentFilter(display: display, including: [targetApp], exceptingWindows: [])

// Configure
let config = SCStreamConfiguration()
config.capturesAudio = true
config.sampleRate = 48000
config.channelCount = 2
config.excludesCurrentProcessAudio = true

// Audio-only: minimize video overhead
config.width = 2; config.height = 2
config.minimumFrameInterval = CMTime(value: 1, timescale: CMTimeScale.max)

let stream = SCStream(filter: filter, configuration: config, delegate: self)
try stream.addStreamOutput(self, type: .screen, sampleHandlerQueue: nil)
try stream.addStreamOutput(self, type: .audio, sampleHandlerQueue: audioQueue)
try await stream.startCapture()

macOS 15+: SCRecordingOutput for simplified file recording, config.captureMicrophone for mic capture. macOS 14+: SCContentSharingPicker for system picker UI, SCScreenshotManager for single-frame capture.

For complete API reference, audio writing (AVAssetWriter/AVAudioFile), permissions, and examples, see references/screen-capture-audio.md.

AppKit Interop

struct WebViewWrapper: NSViewRepresentable {
    let url: URL
    func makeNSView(context: Context) -> WKWebView { WKWebView() }
    func updateNSView(_ v: WKWebView, context: Context) {
        v.load(URLRequest(url: url))
    }
}

For hosting SwiftUI in AppKit and advanced bridging, see references/appkit-interop.md.

Architecture

PatternBest ForComplexity
SwiftUI + @ObservableSmall-medium, soloLow
MVVM + @ObservableMedium, teamsMedium
TCALarge, strict testingHigh

See references/architecture.md for all patterns with examples.

References

FileWhen to read
references/fall-2026-releases.mdWWDC 2026 beta stack: macOS 27, Xcode 27, Swift 6.4, Foundation Models next-gen, Core AI, Spatial Preview, mandatory Liquid Glass
SwiftUI & macOS
references/app-lifecycle.mdWindow management, scenes, DocumentGroup, MenuBarExtra gotchas, async termination, LSUIElement issues
references/swiftui-macos.mdSidebar, Inspector, Table, forms, popovers, sheets, search
references/appkit-interop.mdNSViewRepresentable, hosting controllers, AppKit bridging, NSPanel/floating HUD
references/screen-capture-audio.mdScreenCaptureKit, SCStream gotchas, SCStream teardown hazards, AVAudioEngine dual pipeline, AVAssetWriter crash safety, non-interleaved stereo trap, TCC gotchas, CDHash degraded-state after reinstall
references/core-audio-tap.mdCATap for per-process audio: tap-only aggregate (HFP-safe), drift compensation, rate-change anti-pattern, interleaved-stereo frame-count trap, IO proc isolation
references/system-integration.mdKeyboard shortcuts, drag & drop, file access, App Intents, process monitoring, CoreAudio per-process APIs, login items, LSUIElement, idle sleep prevention
references/foundation-models.mdOn-device AI: guided generation, tool calling, streaming
references/architecture.mdMVVM, TCA, dependency injection, project structure
references/testing.mdSwift Testing, exit tests, attachments, UI testing, XCTest migration
references/distribution.mdApp Store, Developer ID, notarization gotchas, nested bundle signing, sandboxing, universal binaries
references/spm-build.mdPackage.swift, Swift Build, plugins, macros, manual .app bundle assembly, mixed ObjC targets, CLT testing
Concurrency
references/approachable-concurrency.mdDefault MainActor isolation, @concurrent, nonisolated async, runtime pitfalls
references/actors-isolation.mdActor model, global actors, custom executors, reentrancy
references/structured-concurrency.mdTask, TaskGroup, async let, cancellation, priority, named tasks
references/sendable-safety.mdSendable protocol, data race safety, @unchecked Sendable + serial queue, @preconcurrency import
references/async-patterns.mdAsyncSequence, AsyncStream, Observations, continuations, Clock
references/migration-guide.mdGCD to async/await, Combine to AsyncSequence, Swift 6 migration
SwiftData
references/models-schema.md@Model, @Attribute options, Codable, transformable, external storage
references/relationships-predicates.mdAdvanced relationships, inverse rules, compound predicates
references/container-context.mdModelContainer, ModelContext, background contexts, undo/redo, batch ops
references/cloudkit-sync.mdCloudKit setup, conflict resolution, sharing, debugging sync
references/migrations.mdVersionedSchema, lightweight/custom migration, Core Data migration

Questions people ask

Which Swift and Xcode versions does this target?
Swift 6.3 (latest 6.3.3, bundled in Xcode 26.6, June 2026), with Xcode 26.6 shipping the macOS 26.5 SDK. macOS 27 / Xcode 27 / Swift 6.4 content lives in a separate fall-2026 references file.
Does it cover on-device AI?
Yes — the Foundation Models section (macOS 26+) shows how to call the on-device ~3B-parameter LLM with LanguageModelSession, including @Generable structured output, with deeper coverage in references/foundation-models.md.
What distribution paths are documented?
App Store (sandboxed), Developer ID with notarytool + stapler notarization, and ad-hoc local builds, with xcodebuild archive/exportArchive command sequences and a comparison table.
What deployment targets are used?
macOS 14+ for SwiftData and @Observable, macOS 15+ for the latest SwiftUI features, macOS 26 for Liquid Glass and Foundation Models.

Related skills

Control this macOS desktop via screenshots, AppleScript, mouse/keyboard automation, OCR/template matching, and verify loops.

5 installs1 stars

This skill should be used when the user asks about Apple app data via the native Swift MCP — Calendar, Reminders, Contacts, Maps, Mail, Messages, Notes, or Photos on macOS. Triggers on phrases like "check my calendar", "find contact", "send iMessage", "search my notes", "recent emails", "find photos of", or any macOS-native app automation. Requires macOS 14+ on Apple Silicon; faster than the AppleScript-backed Node variant.

12 installs

iOS/macOS 应用全生命周期开发技能包。覆盖从需求分析到上架发布的完整流程,包括:工程工作流(需求澄清、PRD生成、任务拆解、Swift TDD、Bug诊断、架构改进)、政策合规监控与动态学习、智能代码生成(Swift/SwiftUI/UIKit)、UI设计系统与美学规范(12大设计法则、631配色、8点网...

1 installs

Build and debug ARKit features for visionOS, including ARKitSession setup, authorization, data providers (world tracking, plane detection, scene reconstructi...

16 installs

Index of ready-to-run Swift animation code examples organized by category (Menu, Transition, Indicator, Alert, Animation, Tableview, Collectionview, UI) sour...

1 installs

Diagnose and fix iOS platform issues across lifecycle, entitlements, permissions, push, widgets, and StoreKit.

113 installs6 stars