Agent skill

Swift Patterns

by softspark in softspark/ai-toolkit

Swift/iOS: SwiftUI, Combine, async/await, actors, SPM, Core Data, UIKit interop.

Apache-2.0Auto-check passedMobile

Install Swift Patterns

skills CLI
$ npx skills add softspark/ai-toolkit --skill swift-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install softspark/ai-toolkit swift-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/softspark/ai-toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/app/skills/swift-patterns .claude/skills/swift-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
swift-patterns
GitHub stars
179
Token cost
~3.1k tokens
SKILL.md length
609 words
Files
2
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

Swift/iOS: SwiftUI, Combine, async/await, actors, SPM, Core Data, UIKit interop.

  • Tasks that involve iOS development
  • SKILL.md covers Project Structure, Idioms / Code Style, Error Handling and Testing, plus 4 more sections
  • Calls swift; reaches github.com

What it does

Swift Patterns is an agent skill from softspark/ai-toolkit. Swift/iOS: SwiftUI, Combine, async/await, actors, SPM, Core Data, UIKit interop. Triggers: Swift, SwiftUI, Combine, iOS, Xcode, actor, Core Data, @MainActor, @State.

Its SKILL.md is about 3.1k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files (for example `reference/frameworks.md`).

It sits in Mobile, covering iOS development. It works with iOS, SwiftUI, Xcode and Swift. The repository describes itself as: Professional-grade AI coding toolkit: 94 skills, 44 agents, multi-platform (Claude, Cursor, Windsurf, Copilot, Gemini, Cline, Roo Code, Aider, Augment, Antigravity, Codex CLI… The licence is Apache-2.0.

When your agent uses it

  • Tasks that involve iOS development

Example prompts

  • “/swift-patterns”

Requirements

  • Pre-approved tools (allowed-tools): Read

What it can do on your machine

Read from SKILL.md and the folder at commit d64db2b. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • swift

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Swift Patterns loads about 3.1k tokens when it runs. Until then it costs about 45 tokens; SKILL.md has 609 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~45
When it runs · the whole SKILL.md, loaded when a task matches
~3.1k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from softspark/ai-toolkit at commit d64db2b, republished under its Apache-2.0 licence (© softspark). 609 words, ~3,134 tokens.

Download SKILL.mdSave it as .claude/skills/swift-patterns/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
swift-patterns
description
Swift/iOS: SwiftUI, Combine, async/await, actors, SPM, Core Data, UIKit interop. Triggers: Swift, SwiftUI, Combine, iOS, Xcode, actor, Core Data, @MainActor, @State.
allowed-tools
Read
effort
medium
user-invocable
false

Swift / iOS Patterns

Project Structure

Swift Package (SPM)
MyPackage/
├── Package.swift
├── Sources/
│   ├── MyLibrary/
│   └── MyExecutable/
├── Tests/
│   └── MyLibraryTests/
└── Plugins/
swift
// swift-tools-version: 5.10
import PackageDescription

let package = Package(
    name: "MyPackage",
    platforms: [.iOS(.v17), .macOS(.v14)],
    products: [
        .library(name: "MyLibrary", targets: ["MyLibrary"]),
    ],
    dependencies: [
        .package(url: "https://github.com/apple/swift-algorithms", from: "1.2.0"),
    ],
    targets: [
        .target(name: "MyLibrary",
                dependencies: [.product(name: "Algorithms", package: "swift-algorithms")]),
        .testTarget(name: "MyLibraryTests", dependencies: ["MyLibrary"]),
    ]
)
Xcode Project Layout
MyApp/
├── MyApp/
│   ├── App/             # Entry point, ContentView
│   ├── Features/        # Feature modules (Views, ViewModels, Models)
│   ├── Core/            # Networking, Storage, Extensions
│   └── Resources/       # Assets.xcassets, Info.plist
├── MyAppTests/
└── MyAppUITests/

Idioms / Code Style

Optionals
swift
// guard-let for early exit
func process(user: User?) {
    guard let user else { return }
    print(user.name)
}

// Optional chaining + nil coalescing
let name = user?.profile?.displayName ?? "Anonymous"

// map/flatMap on optionals
let length: Int? = optionalString.map { $0.count }
// Never force-unwrap in production: user!.name
Protocol-Oriented Programming
swift
protocol Cacheable: Identifiable where ID: Hashable {
    var cacheKey: String { get }
}

extension Cacheable where ID == String {
    var cacheKey: String { id }
}
Value Types vs Reference Types

Use structs by default (value semantics, thread-safe). Use classes when identity matters, shared mutable state is intentional, inheritance is needed, or ObjC interop is required.

Property Wrappers
swift
@propertyWrapper
struct Clamped<Value: Comparable> {
    var wrappedValue: Value {
        didSet { wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound) }
    }
    let range: ClosedRange<Value>

    init(wrappedValue: Value, _ range: ClosedRange<Value>) {
        self.range = range
        self.wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }
}

struct Volume {
    @Clamped(0...100) var level: Int = 50
}
Result Builders
swift
@resultBuilder
struct ArrayBuilder<Element> {
    static func buildBlock(_ components: [Element]...) -> [Element] { components.flatMap { $0 } }
    static func buildExpression(_ expression: Element) -> [Element] { [expression] }
    static func buildOptional(_ component: [Element]?) -> [Element] { component ?? [] }
}

Error Handling

throws / try / catch
swift
enum NetworkError: Error, LocalizedError {
    case invalidURL
    case timeout(seconds: Int)
    case serverError(statusCode: Int)

    var errorDescription: String? {
        switch self {
        case .invalidURL: "Invalid URL."
        case .timeout(let s): "Timed out after \(s)s."
        case .serverError(let code): "Server returned \(code)."
        }
    }
}

do {
    let user = try fetchUser(id: "123")
} catch let error as NetworkError {
    handleNetworkError(error)
} catch {
    handleUnexpected(error)
}

let user = try? fetchUser(id: "123") // nil on error
Result Type
swift
switch fetchData(from: url) {
case .success(let data): process(data)
case .failure(let error): showError(error)
}
Typed Throws (Swift 6) and Async Throws
swift
func load() throws(DatabaseError) -> [Item] { /* compiler-enforced error type */ }

func fetchUser(id: String) async throws -> User {
    let (data, response) = try await URLSession.shared.data(from: url)
    guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
        throw NetworkError.serverError(statusCode: 0)
    }
    return try JSONDecoder().decode(User.self, from: data)
}

Testing

XCTest
swift
final class UserServiceTests: XCTestCase {
    var sut: UserService!
    var mockRepo: MockUserRepository!

    override func setUp() {
        mockRepo = MockUserRepository()
        sut = UserService(repository: mockRepo)
    }

    func testFetchUser_success() async throws {
        mockRepo.stubbedUser = User(id: "1", name: "Alice")
        let user = try await sut.fetchUser(id: "1")
        XCTAssertEqual(user.name, "Alice")
    }

    func testFetchUser_notFound_throws() async {
        mockRepo.shouldFail = true
        do {
            _ = try await sut.fetchUser(id: "999")
            XCTFail("Expected error")
        } catch {
            XCTAssertTrue(error is UserService.Error)
        }
    }
}
Swift Testing Framework (Swift 6+)
swift
import Testing

@Suite("UserService")
struct UserServiceTests {
    @Test("fetches user by ID")
    func fetchUser() async throws {
        let mockRepo = MockUserRepository()
        mockRepo.stubbedUser = User(id: "1", name: "Alice")
        let sut = UserService(repository: mockRepo)
        let user = try await sut.fetchUser(id: "1")
        #expect(user.name == "Alice")
    }

    @Test("throws on missing user", arguments: ["999", ""])
    func fetchMissingUser(id: String) async {
        let sut = UserService(repository: MockUserRepository())
        await #expect(throws: UserService.Error.self) {
            try await sut.fetchUser(id: id)
        }
    }
}
Protocol-Based Mocking
swift
protocol UserRepository {
    func fetch(id: String) async throws -> User
}

final class MockUserRepository: UserRepository {
    var stubbedUser: User?
    var shouldFail = false
    private(set) var fetchCallCount = 0

    func fetch(id: String) async throws -> User {
        fetchCallCount += 1
        if shouldFail { throw NSError(domain: "", code: 0) }
        return stubbedUser ?? User(id: id, name: "Default")
    }
}
UI Testing
swift
func testLoginFlow() {
    let app = XCUIApplication()
    app.launchArguments = ["--uitesting"]
    app.launch()
    app.textFields["email"].tap()
    app.textFields["email"].typeText("user@example.com")
    app.secureTextFields["password"].typeText("pass")
    app.buttons["Sign In"].tap()
    XCTAssertTrue(app.staticTexts["Welcome"].waitForExistence(timeout: 5))
}

Common Frameworks

For SwiftUI + @Observable, Combine, Structured Concurrency, SwiftData, and Vapor framework patterns with complete code examples, see reference/frameworks.md.


Performance

Copy-on-Write

Array, String, Dictionary use COW automatically. For custom value types:

swift
struct LargeData {
    private final class Storage { var buffer: [UInt8]; init(_ b: [UInt8]) { buffer = b } }
    private var storage: Storage

    var buffer: [UInt8] {
        get { storage.buffer }
        set {
            if !isKnownUniquelyReferenced(&storage) { storage = Storage(newValue) }
            else { storage.buffer = newValue }
        }
    }
}
ARC Retain Cycles
swift
// weak — closure may outlive self
service.fetch { [weak self] result in
    guard let self else { return }
    self.update(with: result)
}

// unowned — self guaranteed to outlive closure
lazy var tick: () -> Void = { [unowned self] in self.count += 1 }
Sendable and Actors
swift
struct Config: Sendable { let apiURL: URL; let timeout: TimeInterval }

actor ImageCache {
    private var cache: [URL: Data] = [:]
    func image(for url: URL) -> Data? { cache[url] }
    func store(_ data: Data, for url: URL) { cache[url] = data }
}
Instruments
InstrumentUse For
Time ProfilerCPU bottlenecks
AllocationsMemory growth
LeaksRetain cycles
SwiftUIView body re-evaluations
Core AnimationFPS, offscreen rendering

Profile on device (not simulator). Use os_signpost for custom spans.


Build / Package Management

SPM Commands
bash
swift package resolve       # Resolve deps
swift build -c release      # Release build
swift test --filter MyTests # Filtered test run
xcconfig
// Shared.xcconfig
SWIFT_VERSION = 5.10
IPHONEOS_DEPLOYMENT_TARGET = 17.0
SWIFT_STRICT_CONCURRENCY = complete

// Debug.xcconfig
#include "Shared.xcconfig"
SWIFT_OPTIMIZATION_LEVEL = -Onone
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG

// Release.xcconfig
#include "Shared.xcconfig"
SWIFT_OPTIMIZATION_LEVEL = -O
SWIFT_COMPILATION_MODE = wholemodule
Tuist

Define targets in Project.swift using ProjectDescription. Map each app, framework, and test target with bundleId, sources, and dependencies. Use .external(name:) for SPM deps and .target(name:) for internal.

Schemes: separate Debug/Release/Testing. Enable ASan + TSan in test schemes.


Anti-Patterns

Anti-PatternProblemFix
Force unwrap !Runtime crashguard let, if let, ??
Massive view controllerUntestableMVVM, composable views
Stringly-typed APIsNo compiler checksEnums, phantom types
Ignoring @MainActorOff-main-thread UIAnnotate view models
Retain cyclesMemory leaks[weak self] / [unowned self]
Blocking main threadUI freezesasync/await, Task { }
UserDefaults for secretsInsecureKeychain (SecItemAdd)
@ObservedObject for owned stateObject recreated@StateObject or @State + @Observable

Rules

  • MUST use Swift concurrency primitives (async/await, actors, Task) for new code — GCD is legacy and mixes poorly with the new model
  • MUST annotate view models with @MainActor when they touch UI state — off-main mutations cause runtime warnings and flaky UI
  • NEVER force-unwrap (!) without a documented invariant in a comment; runtime crashes from unwrap are the top iOS crash category
  • NEVER store secrets in UserDefaults or plist — use Keychain APIs (SecItemAdd, SecItemCopyMatching)
  • CRITICAL: SwiftUI state flows downward; mutations flow through @State, @Binding, or @Observable. Never mutate a parent's state from a child via a captured reference — it breaks dependency tracking.
  • MANDATORY: every closure that captures self inside a reference type uses [weak self] or [unowned self] — retain cycles are the top memory-leak cause
Show full SKILL.md (232 more words)Show less

Gotchas

  • @StateObject and @ObservedObject look similar but behave oppositely on parent re-render: @StateObject persists, @ObservedObject may re-initialize. Using @ObservedObject for view-owned state recreates the object on every render — state loss without error.
  • Task { @MainActor in ... } inside a non-@MainActor context does not synchronously return to main; it schedules. Code between the await and Task boundary runs on whatever actor you came from, which can race with UI updates.
  • AsyncStream continuations without onTermination leak: if the consumer cancels, the producer keeps yielding forever. Always install a termination handler.
  • SwiftData @Query with @Environment(\.modelContext) invalidates on every write; heavy reads in a watched view cause perf drops. Use @FetchRequest-style fetch descriptors with explicit refresh, not ambient @Query, for large datasets.
  • Combine's .receive(on: DispatchQueue.main) schedules asynchronously — if the next operator expects sync execution, order matters. Prefer moving .receive(on:) to just before the sink, not mid-pipeline.
  • Swift Concurrency does not compose cleanly with Objective-C completion handlers; withCheckedContinuation bridges but a continuation that is never resumed hangs the Task forever. Always pair resumes with all control-flow paths, including errors.

When NOT to Load

  • For Flutter or React Native cross-platform code — use /flutter-patterns or JS patterns; this skill is Swift-only
  • For generic iOS architecture decisions (MVC vs MVVM vs VIPER) — use /architecture-decision
  • For Kotlin-based cross-platform mobile (KMP) — use /kotlin-patterns
  • For mobile CI/CD specifics (TestFlight, Fastlane) — use /ci-cd-patterns
  • For Objective-C interop deep dives — outside scope; this skill focuses on modern Swift

© softspark, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in app/skills/swift-patterns of softspark/ai-toolkit.

  • SKILL.md
  • reference/frameworks.md

Open the folder on GitHubat commit d64db2b

Compare with similar skills

Swift Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Swift Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Swift Patterns this skillsoftspark/ai-toolkit179—~3.1kAutomated safety check: PassApache-2.0
Bootstrap iOSRayFernando1337/rayfernando-skills130—~1.1kAutomated safety check: PassApache-2.0
Swift Developmentaiskillstore/marketplace430—~1.8kAutomated safety check: PassNone
Apollo iOSapollographql/skills116—~2kAutomated safety check: PassMIT
Update Swiftui APIsAvdLee/SwiftUI-Agent-Skill3.7k—~1.2kAutomated safety check: PassMIT
Swiftui Expert SkillAFK-surf/OpenBridge4302 repos~3.9kAutomated safety check: PassMIT

Similar skills

  • Bootstrap iOS

    RayFernando1337/rayfernando-skills

    Bootstrap agents for iOS, iPadOS, macOS, Swift, SwiftUI, SwiftData/Core Data, Swift Testing, Xcode build/test/debug, Simulator, App Intents, or XcodeBuildMCP work.

    130 GitHub stars~1.1k tokensUpdated 2 mo ago
    MobileAuto-check passed
  • Swift Development

    aiskillstore/marketplace

    Comprehensive Swift development for building, testing, and deploying iOS/macOS applications.

    430 GitHub stars~1.8k tokensUpdated today
    MobileAuto-check passed
  • Apollo iOS

    apollographql/skills

    Guide for building Apple-platform applications with Apollo iOS, the strongly-typed GraphQL client for Swift.

    116 GitHub stars~2k tokensUpdated today
    Backend & APIsAuto-check passed
  • Update Swiftui APIs

    AvdLee/SwiftUI-Agent-Skill

    Scan Apple's SwiftUI documentation for deprecated APIs and update the SwiftUI Expert Skill with modern replacements.

    3.7k GitHub stars~1.2k tokensUpdated yesterday
    MobileAuto-check passed
  • Swiftui Expert Skill

    AFK-surf/OpenBridge

    Write, review, or improve SwiftUI code following best practices for state management, view composition, performance, modern APIs, Swift concurrency, and iOS 26+ Liquid Glass adoption.

    430 GitHub starsUsed in 2 repos~3.9k tokens
    MobileAuto-check passed
  • SwiftUI Design Skill

    Wholiver/swiftui-design-skill

    Guides the agent to design distinctive SwiftUI interfaces for iOS and macOS, with six anti-generic rules, a design direction workflow and a five-dimension review.

    210 GitHub stars~2.8k tokensUpdated 5 mo ago
    MobileAuto-check passed

More from softspark/ai-toolkit

All 112 skills in this repo
  • Prepare Test Env

    softspark/ai-toolkit

    Prepare or verify a project QA environment with source identity, readiness, browser access, evidence paths and owned cleanup.

    179 GitHub stars~1.8k tokensUpdated today
    Auto-check: notes
  • A11y Validate

    softspark/ai-toolkit

    Accessibility validator: WCAG 2.1 AA, EN 301 549, EAA. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.8k tokensUpdated today
    Auto-check: notes
  • Analyze

    softspark/ai-toolkit

    Analyzes code quality, complexity, patterns across codebase.

    179 GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Autonomous Dev

    softspark/ai-toolkit

    Drives a brief, specification, issue or existing PR through implementation, review, tests and QA to a ready PR.

    179 GitHub stars~2.6k tokensUpdated today
    Auto-check: notes
  • Brand Voice

    softspark/ai-toolkit

    Direct technical voice for docs, README, user-facing text. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~2.1k tokensUpdated today
    Auto-check passed
  • CI

    softspark/ai-toolkit

    Detect/generate/debug CI pipeline config (GitHub Actions, GitLab CI).

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check: notes

Categories

Questions about Swift Patterns

What does Swift Patterns do?

Swift/iOS: SwiftUI, Combine, async/await, actors, SPM, Core Data, UIKit interop. Swift Patterns is an agent skill from softspark/ai-toolkit. Swift/iOS: SwiftUI, Combine, async/await, actors, SPM, Core Data, UIKit interop.

When should I use Swift Patterns?

Swift Patterns fits situations like: tasks that involve iOS development.

How do I install Swift Patterns in Claude Code?

Run `npx skills add softspark/ai-toolkit --skill swift-patterns -a claude-code`. Or copy the skill folder (app/skills/swift-patterns in softspark/ai-toolkit) into .claude/skills/swift-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Swift Patterns in Codex?

Run `npx skills add softspark/ai-toolkit --skill swift-patterns -a codex`. Or copy the skill folder (app/skills/swift-patterns in softspark/ai-toolkit) into .agents/skills/swift-patterns in your project. Codex loads it when a task matches its description.

Can I use Swift Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add softspark/ai-toolkit --skill swift-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/swift-patterns, .gemini/skills/swift-patterns, .github/skills/swift-patterns and .opencode/skills/swift-patterns in your project.

What does Swift Patterns need to run?

Going by SKILL.md and its folder, Swift Patterns needs the command-line tools its instructions call (swift). Its frontmatter pre-approves these tools: Read.

Does Swift Patterns access the network?

SKILL.md names 1 domain. In commands or code: github.com; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Swift Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Swift Patterns use?

Swift Patterns is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Swift Patterns use?

About 3.1k tokens (SKILL.md is roughly 13k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Swift Patterns?

Skills that share tags, products or a category with Swift Patterns: Bootstrap iOS (RayFernando1337/rayfernando-skills, 130 stars), Swift Development (aiskillstore/marketplace, 430 stars), Apollo iOS (apollographql/skills, 116 stars) and Update Swiftui APIs (AvdLee/SwiftUI-Agent-Skill, 3.7k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Swift Patterns?

softspark (a GitHub user) maintains it in softspark/ai-toolkit, which has 179 GitHub stars. The repository holds 112 skills in this directory. The repository was last updated on October 7, 2026.

Source: softspark/ai-toolkit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.