Swift development

From sammcj/agentic-coding · View interactive version

Swift development is an AI agent skill from the GitHub repository sammcj/agentic-coding. You MUST activate this skill when working on Swift projects

How to use this skill

Skill file

Swift Best Practices Skill

Overview

Apply modern Swift development best practices focusing on Swift 6+ features, concurrency safety, API design principles, and code quality guidelines for iOS and macOS projects targeting macOS 15.7+.

When to Use This Skill

Use this skill when:

Core Guidelines

Fundamental Principles

  1. Clarity at point of use is paramount - evaluate designs by examining use cases, not just declarations
  2. Clarity over brevity - compact code comes from the type system, not minimal characters
  3. Write documentation for every public declaration - if you can't describe functionality simply, the API may be poorly designed
  4. Name by role, not type - var greeting = "Hello" not var string = "Hello"
  5. Favour elegance through simplicity - avoid over-engineering unless complexity genuinely warrants it

Swift 6 Concurrency Model

Swift 6 enables complete concurrency checking by default with region-based isolation (SE-0414). The compiler now proves code safety, eliminating many false positives whilst catching real concurrency issues at compile time.

Critical understanding:

Essential Patterns

Async/Await
// Parallel execution with async let
func fetchData() async -> (String, Int) {
    async let stringData = fetchString()
    async let intData = fetchInt()
    return await (stringData, intData)
}

// Always check cancellation in long-running operations
func process(_ items: [Item]) async throws -> [Result] {
    var results: [Result] = []
    for item in items {
        try Task.checkCancellation()
        results.append(await process(item))
    }
    return results
}
MainActor for UI Code
// Apply at type level for consistent isolation
@MainActor
class ContentViewModel: ObservableObject {
    @Published var images: [UIImage] = []

    func fetchData() async throws {
        self.images = try await fetchImages()
    }
}

// Avoid MainActor.run when direct await works
await doMainActorStuff()  // Good
await MainActor.run { doMainActorStuff() }  // Unnecessary
Actor Isolation
actor DataCache {
    private var cache: [String: Data] = [:]

    func store(_ data: Data, forKey key: String) {
        cache[key] = data  // No await needed inside actor
    }

    nonisolated func cacheType() -> String {
        return "DataCache"  // No await needed - doesn't access isolated state
    }
}

Common Pitfalls to Avoid

  1. Don't mark functions as async unnecessarily - async calling convention has overhead
  2. Never use DispatchSemaphore with async/await - risk of deadlock
  3. Don't create stateless actors - use non-isolated async functions instead
  4. Avoid split isolation - don't mix isolation domains within one type
  5. Check task cancellation - long operations must check Task.checkCancellation()
  6. Don't assume async means background - explicitly move work to background if needed
  7. Avoid excessive context switching - group operations within same isolation domain

AppKit Gotchas

Menu-bar app windows open behind everything / hide on click-away. Two separate causes, usually hit together:

Fix both: switch to .regular while the window is open, clear hidesOnDeactivate, then revert on NSWindow.willCloseNotification.

NSApp.setActivationPolicy(.regular)
NSApp.activate()
openSettings()
DispatchQueue.main.async {          // window does not exist until SwiftUI opens it
    guard let w = NSApp.windows.first(where: {
        $0.identifier?.rawValue.hasPrefix("com_apple_SwiftUI_Settings") == true }) else { return }
    w.hidesOnDeactivate = false
    w.makeKeyAndOrderFront(nil)
    w.orderFrontRegardless()
}
// On willCloseNotification: NSApp.setActivationPolicy(.accessory)

Cost: a Dock icon while the window is open. SettingsLink cannot do this - it has no action hook, so use @Environment(\.openSettings).

JSONEncoder.dateEncodingStrategy = .iso8601 truncates to whole seconds. Silently breaks any sub-second timing logic. Use .custom with ISO8601DateFormatter + .withFractionalSeconds.

API Design Quick Reference

Naming Conventions
Method Naming by Side Effects
Argument Labels

Swift 6 Breaking Changes

Must Explicitly Mark Types with @MainActor (SE-0401)

Property wrappers no longer infer actor isolation automatically.

@MainActor
struct LogInView: View {
    @StateObject private var model = ViewModel()
}
Global Variables Must Be Concurrency-Safe (SE-0412)
static let config = Config()  // Constant - OK
@MainActor static var state = State()  // Actor-isolated - OK
nonisolated(unsafe) var cache = [String: Data]()  // Unsafe - use with caution
Other Changes

API Availability Patterns

// Basic availability
@available(macOS 15, iOS 18, *)
func modernAPI() { }

// Deprecation with message
@available(*, deprecated, message: "Use newMethod() instead")
func oldMethod() { }

// Renaming with auto-fix
@available(*, unavailable, renamed: "newMethod")
func oldMethod() { }

// Runtime checking
if #available(iOS 18, *) {
    // iOS 18+ code
}

// Inverted checking (Swift 5.6+)
if #unavailable(iOS 18, *) {
    // iOS 17 and lower
}

Key differences:

How to Use This Skill

When Writing Code

  1. Apply naming conventions following role-based, clarity-first principles
  2. Use appropriate isolation (@MainActor for UI, actors for mutable state)
  3. Implement async/await patterns correctly with proper cancellation handling
  4. Follow Swift 6 concurrency model - trust compiler's flow analysis
  5. Document public APIs with clear, concise summaries

When Reviewing Code

  1. Check for concurrency safety violations
  2. Verify proper actor isolation and Sendable conformance
  3. Ensure async functions handle cancellation appropriately
  4. Validate API naming follows Swift guidelines
  5. Confirm availability annotations are correct for target platforms

Code Quality Standards

Resources

references/

Detailed reference material to load when in-depth information is needed:

Load these references when detailed information is needed beyond the core guidelines provided above.

Platform Requirements

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.