Token导航 LogoToken导航TokenDH.com
开发规范需要联网github未标认证来源可访问许可证需确认审计通过

swift-best-practicesSwift 最佳实践

Agent Skill

swift-best-practices 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,512

周安装

63

GitHub Stars

125

下载量

504
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:swift-best-practices(Swift 最佳实践)
来源仓库:https://github.com/sammcj/agentic-coding
仓库路径:skills/swift-best-practices
安装命令:
npx skills add https://github.com/sammcj/agentic-coding --skill swift-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/sammcj/agentic-coding --skill swift-best-practices

简介

swift-best-practices 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。

  • 它帮助 Agent 结构化地保存失败案例、反馈和改进点,形成可复用的知识库。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装,具体路径为 skills/swift-best-practices。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

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:

  • Writing new Swift code for iOS or macOS applications
  • Reviewing Swift code for correctness, safety, and style
  • Implementing Swift concurrency features (async/await, actors, MainActor)
  • Designing Swift APIs and public interfaces
  • Migrating code from Swift 5 to Swift 6
  • Addressing concurrency warnings, data race issues, or compiler errors related to Sendable/isolation
  • Working with modern Swift language features introduced in Swift 6 and 6.2

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:

  • Async ≠ background - async functions can suspend but don't automatically run on background threads
  • Actors protect mutable shared state through automatic synchronisation
  • @MainActor ensures UI-related code executes on the main thread
  • Global actor-isolated types are automatically Sendable

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

API Design Quick Reference

Naming Conventions

  • Types/protocols: UpperCamelCase
  • Everything else: lowerCamelCase
  • Protocols describing capabilities: -able, -ible, -ing suffixes (Equatable, ProgressReporting)
  • Factory methods: Begin with make (x.makeIterator())
  • Mutating pairs: imperative vs past participle (x.sort() / x.sorted())

Method Naming by Side Effects

  • No side effects: Noun phrases (x.distance(to: y))
  • With side effects: Imperative verbs (x.append(y), x.sort())

Argument Labels

  • Omit when arguments can't be distinguished: min(number1, number2)
  • Value-preserving conversions omit first label: Int64(someUInt32)
  • Prepositional phrases label at preposition: x.removeBoxes(havingLength: 12)
  • Label all other arguments

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

  • @UIApplicationMain/@NSApplicationMain deprecated (use @main)
  • any required for existential types
  • Import visibility requires explicit access control

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:

  • deprecated - Warning, allows usage
  • obsoleted - Error from specific version
  • unavailable - Error, completely prevents usage

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

  • Minimise comments - code should be self-documenting where possible
  • Avoid over-engineering and unnecessary abstractions
  • Use meaningful variable names based on role, not type
  • Follow established project architecture and patterns
  • Prefer count(where:) over filter().count
  • Use InlineArray for fixed-size, performance-critical data
  • Trust compiler's concurrency flow analysis - avoid unnecessary Sendable conformances

Resources

references/

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

  • api-design.md - Complete API design conventions, documentation standards, parameter guidelines, and naming patterns
  • concurrency.md - Detailed async/await patterns, actor best practices, common pitfalls, performance considerations, and thread safety patterns
  • swift6-features.md - New language features in Swift 6/6.2, breaking changes, migration strategies, and modern patterns
  • availability-patterns.md - Comprehensive @available attribute usage, deprecation strategies, and platform version management

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

Platform Requirements

  • Swift 6.0+ compiler for Swift 6 features
  • Swift 6.2+ for InlineArray and enhanced concurrency features
  • macOS 15.7+ with appropriate SDK
  • iOS 18+ for latest platform features
  • Use #available for runtime platform detection
  • Use @available for API availability marking

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.41%
按下载量换算184

Claude

29.61%
按下载量换算149

Cursor

17.05%
按下载量换算86

Gemini CLI

10.28%
按下载量换算52

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills