Token导航 LogoToken导航TokenDH.com
前端设计可写文件github未标认证来源可访问clear审计通过

swift-conventionsSwift conventions 前端

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

416

周安装

17

GitHub Stars

8

下载量

133
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/kaakati/rails-enterprise-dev --skill swift-conventions

简介

swift-conventions 用于辅助前端页面、组件和样式开发,适合 React、Vue 等项目维护。

  • 可生成或审查组件代码,整理结构并定位布局和性能问题。
  • 需结合项目现有设计系统、路由和构建方式使用,避免生成孤立片段。
  • 涉及页面改动时应配合本地预览和构建检查确认视觉效果。
  • 支持 Tailwind、CSS 等主流技术栈的代码辅助。

SKILL.md

Swift Conventions — Expert Decisions

Expert decision frameworks for Swift choices that require experience. Claude knows Swift syntax — this skill provides the judgment calls.


Decision Trees

Struct vs Class

Need shared mutable state across app?
├─ YES → Class (singleton pattern, session managers)
└─ NO
   └─ Need inheritance hierarchy?
      ├─ YES → Class (UIKit subclasses, NSObject interop)
      └─ NO
         └─ Data model or value type?
            ├─ YES → Struct (User, Configuration, Point)
            └─ NO → Consider what identity means
               ├─ Same instance matters → Class
               └─ Same values matters → Struct

The non-obvious trade-off: Structs with reference-type properties (arrays, classes inside) lose copy-on-write benefits. A struct containing [UIImage] copies the array reference, not images — mutations affect all "copies."

async/await vs Combine vs Callbacks

Is this a one-shot operation? (fetch user, save file)
├─ YES → async/await (cleaner, better stack traces)
└─ NO → Is it a stream of values over time?
   ├─ YES
   │  └─ Need transformations/combining?
   │     ├─ Heavy transforms → Combine (map, filter, merge)
   │     └─ Simple iteration → AsyncStream
   └─ NO → Must support iOS 14?
      ├─ YES → Combine or callbacks
      └─ NO → async/await with continuation

When Combine still wins: Multiple publishers needing combineLatest, merge, or debounce. Converting this to pure async/await requires manual coordination that Combine handles elegantly.

@MainActor Placement

Is every public method UI-related?
├─ YES → @MainActor on class/struct
└─ NO
   └─ Does it manage UI state? (@Published, bindings)
      ├─ YES → @MainActor on class, nonisolated for non-UI methods
      └─ NO
         └─ Only some methods touch UI?
            ├─ YES → @MainActor on specific methods
            └─ NO → No @MainActor needed

Critical: @Published properties MUST be updated on MainActor. SwiftUI observes on main thread — background updates cause undefined behavior, not just warnings.

TaskGroup vs async let

Number of concurrent operations known at compile time?
├─ YES (2-5 fixed operations) → async let
│  Example: async let user = fetchUser()
│           async let posts = fetchPosts()
│
└─ NO (dynamic count, array of IDs) → TaskGroup
   Example: for id in userIds { group.addTask { ... } }

async let gotcha: All async let values MUST be awaited before scope ends. Forgetting to await silently cancels the task — no error, just missing data.


NEVER Do

Memory & Retain Cycles

NEVER capture self strongly in stored closures:

// ❌ Retain cycle — ViewModel never deallocates
class ViewModel {
    var onUpdate: (() -> Void)?

    func setup() {
        onUpdate = { self.refresh() } // self → onUpdate → self
    }
}

// ✅ Break with weak capture
onUpdate = { [weak self] in self?.refresh() }

NEVER use unowned unless you can PROVE the reference outlives the closure. When in doubt, use weak. The crash from dangling unowned is worse than the nil-check cost.

NEVER forget Timer invalidation:

// ❌ Timer retains target — object never deallocates
timer = Timer.scheduledTimer(target: self, selector: #selector(tick), ...)

// ✅ Block-based with weak capture + invalidate in deinit
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
    self?.tick()
}
deinit { timer?.invalidate() }

Concurrency

NEVER access @Published from background:

// ❌ Undefined behavior — may work sometimes, crash others
Task.detached {
    viewModel.isLoading = false // Background thread!
}

// ✅ Explicit MainActor
Task { @MainActor in
    viewModel.isLoading = false
}

NEVER use Task {} for fire-and-forget without understanding cancellation:

// ❌ Task inherits actor context — may block UI
func buttonTapped() {
    Task { await heavyOperation() } // Runs on MainActor!
}

// ✅ Explicit detachment for background work
func buttonTapped() {
    Task.detached(priority: .userInitiated) {
        await heavyOperation()
    }
}

NEVER assume Task.cancel() stops execution immediately. Cancellation is cooperative — your code must check Task.isCancelled or use try Task.checkCancellation().

Optionals

NEVER force-unwrap in production code except:

  1. @IBOutlet — set by Interface Builder
  2. URL(string: "https://known-valid.com")! — compile-time known strings
  3. fatalError paths where crash is correct behavior

NEVER use implicitly unwrapped optionals (var user: User!) for regular properties. Only valid for:

  • @IBOutlet connections
  • Two-phase initialization where value is set immediately after init

Protocol Design

NEVER make protocols require AnyObject unless you need weak references:

// ❌ Unnecessarily restricts to classes
protocol DataProvider: AnyObject {
    func fetchData() -> Data
}

// ✅ Only require AnyObject for delegates that need weak reference
protocol ViewModelDelegate: AnyObject { // Needed for weak var delegate
    func viewModelDidUpdate()
}

NEVER add default implementations that change protocol semantics:

// ❌ Dangerous — conformers might not override
protocol Validator {
    func validate() -> Bool
}
extension Validator {
    func validate() -> Bool { true } // Silent "always valid"
}

// ✅ Make requirement obvious or use different name
extension Validator {
    func isAlwaysValid() -> Bool { true } // Clear this is a default
}

iOS-Specific Patterns

Dependency Injection in ViewModels

// ✅ Protocol-based for testability
protocol UserServiceProtocol {
    func fetchUser(id: String) async throws -> User
}

@MainActor
final class UserViewModel: ObservableObject {
    @Published private(set) var user: User?
    @Published private(set) var error: Error?

    private let userService: UserServiceProtocol

    init(userService: UserServiceProtocol = UserService()) {
        self.userService = userService
    }
}

Why default parameter: Production code uses real service, tests inject mock. No container framework needed for most apps.

Property Wrapper Selection

WrapperUse WhenMemory Behavior
@StateView-local primitive/value typesView-owned, recreated on parent rebuild
@StateObjectView creates and owns the ObservableObjectCreated once, survives view rebuilds
@ObservedObjectView receives ObservableObject from parentNot owned, may be recreated
@EnvironmentObjectShared across view hierarchyMust be injected by ancestor
@BindingTwo-way connection to parent's stateReference to parent's storage

The StateObject vs ObservedObject trap: Using @ObservedObject for a locally-created object causes recreation on every view update — losing all state.

Error Handling Strategy

// Domain-specific errors with recovery info
enum UserError: LocalizedError {
    case notFound(userId: String)
    case unauthorized
    case networkFailure(underlying: Error)

    var errorDescription: String? {
        switch self {
        case .notFound(let id): return "User \(id) not found"
        case .unauthorized: return "Please log in again"
        case .networkFailure: return "Connection failed"
        }
    }

    var recoverySuggestion: String? {
        switch self {
        case .notFound: return "Check the user ID and try again"
        case .unauthorized: return "Your session expired"
        case .networkFailure: return "Check your internet connection"
        }
    }
}

Performance Traps

Copy-on-Write Gotchas

// ✅ COW works — array copied only on mutation
var a = [1, 2, 3]
var b = a        // No copy yet
b.append(4)      // Now b gets its own copy

// ❌ COW broken — class inside struct
struct Container {
    var items: NSMutableArray // Reference type!
}
var c1 = Container(items: NSMutableArray())
var c2 = c1      // Both point to same NSMutableArray
c2.items.add(1)  // Mutates c1.items too!

Lazy vs Computed

// lazy: Computed ONCE, stored
lazy var dateFormatter: DateFormatter = {
    let f = DateFormatter()
    f.dateStyle = .medium
    return f
}()

// computed: Computed EVERY access
var formattedDate: String {
    dateFormatter.string(from: date) // Cheap, uses cached formatter
}

Rule: Expensive object creation → lazy. Simple derived values → computed.

String Performance

// ❌ O(n) for each concatenation in loop
var result = ""
for item in items {
    result += item.description // Creates new String each time
}

// ✅ O(n) total
var result = ""
result.reserveCapacity(estimatedLength)
for item in items {
    result.append(item.description)
}

// ✅ Best for joining
let result = items.map(\.description).joined(separator: ", ")

Quick Reference

Access Control Decision

LevelUse When
privateImplementation detail within declaration
fileprivateShared between types in same file (rare)
internalModule-internal, app code default
packageSame package, different module (Swift 5.9+)
publicFramework API, readable outside module
openFramework API, subclassable outside module

Default to most restrictive. Start private, widen only when needed.

Naming Quick Check

  • Types: PascalCase nouns — UserViewModel, NetworkError
  • Protocols: PascalCase — capability (-able/-ible) or description
  • Functions: camelCase verbs — fetchUser(), configure(with:)
  • Booleans: is/has/should/can prefix — isLoading, hasContent
  • Factory methods: make prefix — makeUserViewModel()

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

补充不同宿主或平台的使用分布数据

能力 5

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

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

平台分布

Antigravity

29.26%
按下载量换算39

windsurf

23.79%
按下载量换算32

Claude Code

15.92%
按下载量换算21

OpenCode

12.58%
按下载量换算17

Gemini CLI

7.21%
按下载量换算10

Codex

2.99%
按下载量换算4

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

可写文件

该 Skill 可能写入或修改本地文件,使用前需要确认目标目录和修改范围。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills