Agent skill

Swift Rules

by softspark in softspark/ai-toolkit

Swift coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

Apache-2.0Auto-check passedMobile

Install Swift Rules

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

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

GitHub CLI
$ gh skill install softspark/ai-toolkit swift-rules --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-rules .claude/skills/swift-rules && 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-rules
GitHub stars
179
Token cost
~3.5k tokens
SKILL.md length
1,659 words
Files
1
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

Swift coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit.

  • Tasks that involve iOS development
  • SKILL.md covers Naming, Types, Optionals and Properties, plus 21 more sections
  • Calls swift and xcodebuild

What it does

Swift Rules is an agent skill from softspark/ai-toolkit. Swift coding rules: style, patterns, security, testing. Triggers: .swift, Package.swift, .xcodeproj, SwiftUI, Combine, async/await, XCTest.

Its SKILL.md is about 3.5k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Mobile, covering iOS development. It works with SwiftUI 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-rules”

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
    • xcodebuild

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

  • Network

    No URLs in SKILL.md.

    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 Rules loads about 3.5k tokens when it runs. Until then it costs about 38 tokens; SKILL.md has 1,659 words of instructions outside code blocks.

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

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). 1,659 words, ~3,544 tokens.

Download SKILL.mdSave it as .claude/skills/swift-rules/SKILL.md (or your agent's skills folder).
name
swift-rules
description
Swift coding rules: style, patterns, security, testing. Triggers: .swift, Package.swift, .xcodeproj, SwiftUI, Combine, async/await, XCTest.
allowed-tools
Read
effort
medium
user-invocable
false

Swift Rules

These rules come from app/rules/swift/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Swift. Apply them when writing or reviewing Swift code.

Swift Coding Style

Naming

  • PascalCase: types, protocols, enums, struct, class.
  • camelCase: functions, methods, properties, variables, enum cases.
  • No prefixes: Swift has module namespacing (no NS or UI prefix for your types).
  • Use descriptive names: removeElement(at:) not remove(i:).
  • Boolean properties read as assertions: isEmpty, hasChildren, canSubmit.

Types

  • Prefer struct over class by default (value semantics, no reference cycles).
  • Use class only when reference semantics or inheritance is required.
  • Use enum with associated values for modeling finite states.
  • Use protocol for defining capabilities. Prefer protocol composition.
  • Use typealias for complex generic signatures for readability.

Optionals

  • Use guard let for early exit on nil. Use if let for conditional binding.
  • Never force-unwrap (!) unless failure is a programming error.
  • Use ?? for default values: let name = user?.name ?? "Unknown".
  • Use optional chaining: user?.address?.city.
  • Use map / flatMap on optionals for transformations.

Properties

  • Use let by default. Use var only when mutation is required.
  • Use computed properties for derived values: var fullName: String { ... }.
  • Use property observers (willSet, didSet) for side effects on change.
  • Use lazy var for expensive initialization deferred until first access.
  • Use @Published (Combine) for observable properties in classes.

Functions

  • Use argument labels for clarity: func move(from source: Int, to destination: Int).
  • Omit argument labels when the function name makes the role clear: func contains(_ element: T).
  • Use default parameter values instead of multiple overloads.
  • Use throws / async throws for fallible operations.
  • Use trailing closure syntax for the last closure parameter.

Access Control

  • Use private for implementation details. Use fileprivate sparingly.
  • Use internal (default) for module-scoped access.
  • Use public for framework API. Use open only when subclassing is intended.
  • Prefer private(set) for read-only external access with internal mutation.

Formatting

  • Use SwiftLint for automated style enforcement.
  • Use SwiftFormat for automated code formatting.
  • Commit .swiftlint.yml and .swiftformat to the repository.
  • Max line length: 120 characters (SwiftLint default).
  • Use trailing commas in multi-line arrays and dictionaries.

Swift Frameworks

SwiftUI

  • Use VStack, HStack, ZStack for layout composition.
  • Use List with ForEach for dynamic content. Use LazyVStack for large lists.
  • Use NavigationStack (iOS 16+) with navigationDestination(for:) for type-safe navigation.
  • Use .task { } modifier for async data loading tied to view lifecycle.
  • Use @ViewBuilder for conditional view composition in custom containers.
  • Use PreviewProvider or #Preview macro for rapid UI iteration.

UIKit (Legacy / Hybrid)

  • Use UIHostingController to embed SwiftUI views in UIKit.
  • Use UIViewRepresentable to wrap UIKit views in SwiftUI.
  • Use Auto Layout with constraints or UIStackView for layout.
  • Use UICollectionViewCompositionalLayout for complex collection layouts.
  • Use Coordinator pattern for delegate-based UIKit interop in SwiftUI.

Combine

  • Use Publisher / Subscriber for reactive data streams.
  • Use sink for subscribing. Store cancellables in Set<AnyCancellable>.
  • Use map, filter, flatMap, combineLatest for stream transformation.
  • Use @Published on class properties for automatic publisher generation.
  • Prefer AsyncSequence (async/await) over Combine for new code.

Swift Data

  • Use @Model macro for persistent model definitions.
  • Use @Query in SwiftUI views for automatic fetching and observation.
  • Use ModelContext for CRUD operations: context.insert(item), context.delete(item).
  • Use #Predicate macro for type-safe query filtering.
  • Use ModelConfiguration for custom store locations and migration options.

Core Data (Legacy)

  • Use NSPersistentContainer for stack setup.
  • Use NSFetchRequest with NSPredicate for querying.
  • Use performBackgroundTask for background context operations.
  • Use lightweight migrations for schema changes when possible.
  • Prefer SwiftData for new projects (iOS 17+).

Vapor (Server-Side)

  • Use routes.get("users") for route definitions.
  • Use Content protocol for request/response body codable conformance.
  • Use Fluent ORM with migrations for database access.
  • Use middleware for authentication, CORS, and error handling.
  • Use async/await natively (Vapor 4+ is fully async).

Networking

  • Use URLSession with async/await for HTTP requests.
  • Use Codable with JSONDecoder for response parsing.
  • Use URLCache and ETag for response caching.
  • Set timeoutIntervalForRequest on URLSessionConfiguration.
  • Use TaskLocal for request-scoped values (tracing, auth context).

Package Management

  • Use Swift Package Manager (SPM) for dependency management.
  • Define dependencies in Package.swift with exact version or version ranges.
  • Use Package.resolved committed to the repository for reproducible builds.
  • Prefer SPM over CocoaPods/Carthage for new projects.

Swift Patterns

Error Handling

  • Use enum AppError: Error for typed, exhaustive error handling.
  • Use throws functions with do-catch for recoverable errors.
  • Use Result<Success, Failure> for asynchronous error propagation.
  • Use try? for optional conversion. Use try! only in tests or guaranteed paths.
  • Add LocalizedError conformance for user-facing error messages.

Protocol-Oriented Design

  • Define capabilities as protocols: protocol Fetchable { func fetch() async throws -> Data }.
  • Use protocol extensions for default implementations.
  • Use protocol composition: func process(_ item: Sendable & Codable).
  • Use associated types for generic protocols: associatedtype Output.
  • Use some Protocol (opaque types) for return types hiding concrete implementations.

Async/Await

  • Use async functions for all asynchronous operations.
  • Use async let for concurrent, independent operations.
  • Use TaskGroup for dynamic parallelism with collected results.
  • Use Task { } to bridge sync to async. Avoid .task { } in views for complex logic.
  • Use withThrowingTaskGroup for concurrent operations that can fail.

Actors

  • Use actor for thread-safe mutable state (replaces manual locks).
  • Use @MainActor for UI-related state and methods.
  • Use nonisolated for actor methods that do not access mutable state.
  • Use GlobalActor for custom isolation domains.
  • Minimize await calls on actors to reduce suspension points.

SwiftUI Patterns

  • Use @State for view-local mutable state.
  • Use @Binding for child-to-parent state communication.
  • Use @Observable (Observation framework) for model objects (preferred over @ObservedObject).
  • Use @Environment for dependency injection: @Environment(\.modelContext).
  • Use ViewModifier for reusable view transformations.
  • Extract subviews into separate structs for readability and performance.

Codable

  • Use Codable for JSON serialization/deserialization.
  • Use CodingKeys enum for custom key mapping.
  • Use JSONDecoder with .convertFromSnakeCase for API compatibility.
  • Use @propertyWrapper for custom decoding strategies (e.g., date formats).
  • Use nestedContainer for flattening nested JSON structures.

Dependency Injection

  • Use initializer injection for required dependencies.
  • Use @Environment in SwiftUI for framework-provided values.
  • Use swift-dependencies library for testable, controlled dependency management.
  • Use @Dependency(\.apiClient) var apiClient for automatic resolution.

Anti-Patterns

  • Force-unwrapping optionals: use guard let or ??.
  • Massive view controllers/views: split into subviews and view models.
  • Reference cycles: use [weak self] in closures capturing self.
  • Blocking the main thread: use Task or DispatchQueue.global().
  • Stringly-typed APIs: use enums, protocols, and strong types.
Show full SKILL.md (656 more words)Show less

Swift Security

Keychain

  • Use Keychain Services for storing passwords, tokens, and cryptographic keys.
  • Use kSecAttrAccessibleWhenUnlockedThisDeviceOnly for sensitive items.
  • Use KeychainAccess or similar wrapper libraries for cleaner API.
  • Never store secrets in UserDefaults (unencrypted plist on disk).
  • Delete keychain items on user logout.

App Transport Security (ATS)

  • Use HTTPS for all network connections. ATS enforces this by default.
  • Never add blanket NSAllowsArbitraryLoads exception.
  • Use per-domain exceptions only when connecting to legacy servers.
  • Implement certificate pinning for high-security connections.
  • Validate server certificates in URLSessionDelegate for custom pinning.

Input Validation

  • Validate all user input before processing or displaying.
  • Use NSRegularExpression or Swift Regex for pattern validation.
  • Sanitize strings before using in URL construction, SQL, or HTML.
  • Validate deep link URL parameters before navigation.
  • Limit input lengths in UITextField / TextField to prevent abuse.

Data Protection

  • Use Data Protection API: set FileProtectionType.complete on sensitive files.
  • Use CryptoKit for hashing (SHA256), encryption (AES.GCM), and signing.
  • Use SecureEnclave for hardware-backed key storage on supported devices.
  • Zero sensitive data in memory after use: withUnsafeMutableBytes { $0.initializeMemory(as: UInt8.self, repeating: 0) }.
  • Use @Sendable closures to prevent data races in concurrent access.

Authentication

  • Use AuthenticationServices for Sign in with Apple and passkeys.
  • Use LocalAuthentication (Face ID / Touch ID) for biometric auth.
  • Store authentication tokens in Keychain, not in memory or UserDefaults.
  • Use short-lived access tokens with refresh token rotation.
  • Implement session timeout for inactive users.

Network Security

  • Use URLSession with certificate pinning for sensitive API calls.
  • Validate response Content-Type headers before parsing.
  • Use Codable for structured deserialization (prevents injection).
  • Set request timeouts to prevent hanging connections.
  • Do not log request/response bodies containing sensitive data.

Code Security

  • Use [weak self] in closures to prevent retain cycles and memory leaks.
  • Use @Sendable and actor isolation for thread-safe concurrent code.
  • Avoid UnsafePointer / UnsafeMutablePointer unless absolutely necessary.
  • Use #if DEBUG guards for debug-only code. Never ship debug features.
  • Enable Xcode hardened runtime for macOS apps.

Dependency Security

  • Audit SPM dependencies before adding. Check maintainer reputation.
  • Pin dependency versions in Package.resolved.
  • Review Package.swift of dependencies for unusual build plugins.
  • Prefer dependencies with active security response and disclosure processes.
  • Minimize third-party dependencies for security-critical modules.

Swift Testing

Framework

  • Use Swift Testing (import Testing) for new projects (Swift 5.10+).
  • Use XCTest for existing projects and UIKit-based UI tests.
  • Use swift-snapshot-testing for visual regression testing.
  • Use swift-dependencies for controlled dependency injection in tests.

File Naming

  • Test files: FooTests.swift in Tests/ target.
  • Mirror source module structure in test target.
  • Use @Test attribute (Swift Testing) or test prefix (XCTest) for test methods.
  • Use @Suite (Swift Testing) for test grouping.

Structure (Swift Testing)

  • Use @Test("description") for individual test cases.
  • Use @Test(arguments: [...]) for parameterized tests.
  • Use #expect(condition) for assertions. Use #require(condition) for preconditions.
  • Use #expect(throws: FooError.self) { try riskyOperation() } for error testing.
  • Use @Suite structs for grouping. Properties serve as shared setup.

Structure (XCTest)

  • Use setUp() / tearDown() for per-test initialization and cleanup.
  • Use setUpWithError() for throwing setup code.
  • Use XCTAssertEqual, XCTAssertTrue, XCTAssertNil for assertions.
  • Use XCTAssertThrowsError for exception testing.
  • Use expectation(description:) + wait(for:timeout:) for async assertions.

Async Testing

  • Use async test functions: @Test func fetchUser() async throws { ... }.
  • Use confirmation() (Swift Testing) for event-based async assertions.
  • XCTest: use XCTestExpectation with fulfillment() for callback-based async.
  • Test AsyncSequence with for await loops and assertion on collected values.

Mocking

  • Use protocol-based dependency injection for testability.
  • Create manual mock implementations conforming to protocols.
  • Use swift-dependencies for environment-controlled dependency overrides.
  • Use @Dependency property wrapper for automatic mock injection in tests.
  • Avoid mocking frameworks when protocol mocks are straightforward.

UI Testing (XCTest)

  • Use XCUIApplication for UI automation tests.
  • Use accessibility identifiers for reliable element lookup.
  • Use app.buttons["Submit"].tap() for interaction simulation.
  • Use waitForExistence(timeout:) for async UI element appearance.
  • Keep UI tests focused on critical user flows only (slow to run).

Best Practices

  • Test behavior through public API. Avoid @testable import when possible.
  • Use @testable import Module only when testing internal members is necessary.
  • Use withDependencies { } for scoped dependency overrides in tests.
  • Test on multiple platforms (iOS, macOS) when shipping cross-platform.
  • Run tests with swift test or xcodebuild test in CI.

© 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

Just SKILL.md in app/skills/swift-rules of softspark/ai-toolkit.

Open the folder on GitHubat commit d64db2b

Compare with similar skills

Swift Rules 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 Rules compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Swift Rules this skillsoftspark/ai-toolkit179—~3.5kAutomated safety check: PassApache-2.0
Swiftui Expert SkillAFK-surf/OpenBridge4302 repos~3.9kAutomated safety check: PassMIT
macOS DevelopmentKartikLabhshetwar/better-shot2.4k2 repos~735Automated safety check: PassCustom licence
Implement Featuretddworks/SkillsManager169—~2.6kAutomated safety check: PassNone
Swiftui AnimationAstraFoundry/KumoApp290—~4.1kAutomated safety check: PassAGPL-3.0
Implement Featuretddworks/ClaudeBar1.5k—~4.1kAutomated safety check: PassApache-2.0

Similar skills

  • 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
  • macOS Development

    KartikLabhshetwar/better-shot

    Comprehensive macOS development guidance including Swift 6+, SwiftUI, SwiftData, architecture patterns, AppKit bridging, and macOS 26 Tahoe APIs.

    2.4k GitHub starsUsed in 2 repos~735 tokens
    MobileAuto-check passed
  • Implement Feature

    tddworks/SkillsManager

    Guide for implementing features following architecture-first design, TDD, rich domain models, and Swift 6.2 patterns.

    169 GitHub stars~2.6k tokensUpdated 4 mo ago
    MobileAuto-check passed
  • Swiftui Animation

    AstraFoundry/KumoApp

    Implement, review, or improve SwiftUI animations and transitions.

    290 GitHub stars~4.1k tokensUpdated 4 mo ago
    MobileAuto-check passed
  • Implement Feature

    tddworks/ClaudeBar

    Guide for implementing features in ClaudeBar following architecture-first design, TDD, rich domain models, and Swift 6.2 patterns.

    1.5k GitHub stars~4.1k tokensUpdated today
    MobileAuto-check passed
  • Snapshot Tests

    microsoft/SwiftStreamingMarkdown

    Official

    Record and validate swift-snapshot-testing snapshots in the SwiftStreamingMarkdown package: regenerate reference PNGs, run snapshot tests, and diff failed snapshots.

    377 GitHub stars~2.2k tokensUpdated 12 days 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

Works with

Categories

Questions about Swift Rules

What does Swift Rules do?

Swift coding rules: style, patterns, security, testing. An agent skill from softspark/ai-toolkit. Swift Rules is an agent skill from softspark/ai-toolkit. Swift coding rules: style, patterns, security, testing.

When should I use Swift Rules?

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

How do I install Swift Rules in Claude Code?

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

How do I install Swift Rules in Codex?

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

Can I use Swift Rules 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-rules -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-rules, .gemini/skills/swift-rules, .github/skills/swift-rules and .opencode/skills/swift-rules in your project.

What does Swift Rules need to run?

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

Does Swift Rules access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Swift Rules 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 Rules use?

Swift Rules 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 Rules use?

About 3.5k tokens (SKILL.md is roughly 14k 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 Rules?

Skills that share tags, products or a category with Swift Rules: Swiftui Expert Skill (AFK-surf/OpenBridge, 430 stars), macOS Development (KartikLabhshetwar/better-shot, 2.4k stars), Implement Feature (tddworks/SkillsManager, 169 stars) and Swiftui Animation (AstraFoundry/KumoApp, 290 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Swift Rules?

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.