Communitygithub.com

CharbelElBateh/personal-website

如何编写现代 Swift——值类型建模、Swift 6 数据竞争安全与易用并发 (@concurrent、默认主Actor、Actor、任务组)、协议与泛型 (some vs any)、API 设计、性能与 ARC、Swift Testing、宏,以及智能代理尚未了解的现代语言特性。适用于编写、审查或迁移 Swift 代码,或修复并发错误、挂起、数据竞争、循环引用及性能问题时使用。

personal-website 是什么?

该技能提供了一套完整的现代 Swift 编程指南,截止到 Swift 6.4 版本,以 Swift 6.3 工具链为基础。它强调 Swift 作为一种渐进式语言的设计哲学——始终从最简单、最静态、最单线程的方案开始,仅在必要时才引入动态性(如并发、引用语义、存在类型、不安全指针)。技能涵盖六大核心领域:使用值类型(struct/enum)进行数据建模、错误与可选值的正确处理、从单线程向异步并发的渐进式迁移策略(包括 Swift 6.2 中 async 不自动切换 actor 的关键变化)、Sendable 与数据共享的最佳实践、结构化并发的使用原则(async let、任务组优先于非结构化 Task),以及协议与泛型的深度理解(some vs any 的权衡)。该技能特别适用于撰写或审查代码、迁移旧项目到最新 Swift 版本,以及排查与并发相关的各类 bug(数据竞争、死锁、循环引用、性能问题)。它支持所有主流 Swift 开发环境(Xcode、Swift Playgrounds、命令行工具),并给出了具体的代码示例和构建配置建议。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/CharbelElBateh/personal-website/tree/HEAD/.claude/skills/write-swift

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

编写 Swift

初始响应

首次调用此技能且没有具体问题时,仅回复:

我已准备好帮助您编写现代 Swift,就像这门语言希望被编写那样。

在用户提出问题之前,不要提供任何其他信息。

如何编写 Swift 这门语言希望被编写的方式,截止到 Swift 6.4 版本。

工具链基线:Swift 6.3(截至 2026 年 8 月的当前版本)。除非标有 ⚠(表示尚未发布的 Swift 6.4 特性),此处所有内容均可在 6.3 上编译。并发指南假设使用 Swift 6.2 模型——如果项目基于 6.1 或更早版本,第 3 节中关于 async 和 @concurrent 的规则不适用。

主线:Swift 是一门渐进式语言。从最简单、最静态、最单线程的方案开始,仅在你能指出确切原因时才引入动态性——并发、引用语义、存在类型、不安全指针。 下面的每一条规则都是这一原则的具体应用。

将该默认层级模型化。只有在你能够陈述明确理由时,才向下移动一个层级:

需求优先选择仅当以下情况才向下移动
数据struct / enum需要身份标识、共享或继承
抽象具体类型存在跨类型的重复代码
多态some P (泛型)需要异构存储 → any P
执行主 Actor,同步性能分析显示存在挂起 → async → @concurrent → actor
内存Array, String性能分析显示成本过高 → InlineArray, Span
安全安全 APIC 互操作或经测量的热路径 → Unsafe*

1. 使用值类型建模数据

在 Swift 中,值类型是默认选项,而非特例。

  • 默认使用 struct 和 enum。仅在需要身份标识、共享可变状态、继承或资源生命周期时使用 class。 窗口、数据库连接、渲染引擎中的实体——这些具有身份标识。而 Point、Drink、Material 则没有。
  • 默认使用 let;仅在需要修改时使用 var。 这与 some 先于 any、值先于引用的原则相同:从窄范围开始,有原因时再扩展。
  • 包含可变引用类型属性的结构体既非值类型也非引用类型。 副本共享对象;修改会泄露到副本之间。要么让被引用的类型不可变,要么只暴露转发给它的计算属性,要么将其作为私有存储属性实现写时复制。
  • 写时复制是同时实现外部存储和值语义的方法。 在结构体中包装一个 final 类,并在修改前检查 isKnownUniquelyReferenced(&storage);如果不是唯一引用则先复制。这正是 Array、String 和 Dictionary 的实现方式。
  • 枚举是表示“固定集合”和互斥状态的最佳工具。 用一堆可选存储属性(isSharing、selectedRows、shareTarget)替换为一个 enum State,可以使无效组合不可表示,并将状态变更原子化,而不是一系列可能忘记完成的属性写入。
  • 组合值类型产生的是值类型。 一个所有存储属性都是值类型的结构体自动具有值语义——这使得撤销、差异比较和状态恢复成为单一代码路径,而不是每个属性一个路径。
struct Material {                       // 保持值语义
  var roughness: Double
  private var _texture: Texture         // 一个类

  var color: Color {
    get { _texture.color }
    set {
      if !isKnownUniquelyReferenced(&_texture) { _texture = Texture(copying: _texture) }
      _texture.color = newValue
    }
  }
}

不可复制类型(~Copyable)表示独占所有权:文件描述符、银行转账、打开的源。抑制复制行为将“你不应该运行此代码两次”从断言转变为编译错误,并使结构体中的 deinit 变得有意义。将结束方法标记为 consuming,以便编译器证明这是最后一次使用。参数所有权变得明确:borrowing(只读,默认)、consuming(拿走所有权)、inout/mutating(临时写访问)。


2. 错误与可选值——让失败路径可见

Swift 错误处理基于三个要点:错误的来源被标记,使其不会让你意外;错误携带足够的上下文以便采取行动;可恢复的错误与程序员错误是不同的。

  • 可恢复错误 → throw。程序员错误 → precondition/fatalError。 网络调用失败应让程序继续运行。数组越界意味着代码有误,必须在错误变成安全问题前停止。
  • 带有关联值的枚举是最佳的错误类型。 case duplicateFriend(String) 优于 case duplicateFriend——上下文本身就是关键。
  • 对错误条件使用 guard,因为它强制退出路径。对普通的展开使用 if let。
  • 带类型的抛出(throws(MyError))适用于内部函数、转发错误的泛型代码以及受限环境,其中将 any Error 装箱成本过高。对于公共 API,无类型的 throws 保留了你将来更改错误类型的自由度。注意统一性:throws 就是 throws(any Error),而不抛出是 throws(Never)——这正是 map 能抽象处理两者的原因。
  • 仅在你能够陈述不变量时强制展开,并且优先使用带有信息的 #require/precondition,而不是裸的 !。

3. 并发:在性能分析表明需要之前保持单线程

这是智能代理最常出错的章节,因为模型在 Swift 6.2 中发生了变化。

每个应用都完全在主线程上启动。单线程代码可以走得很远,大多数应用永远不需要离开它。

按照顺序的演进步骤。不要跳过步骤。

  1. 主 Actor 上的单线程执行。 完全没有并发。对大多数应用来说已经足够。
  2. async/await 用于隐藏延迟(网络、磁盘)。仍然没有你自己的并发——像 URLSession.data(from:) 这样的 SDK API 会代表你卸载工作。
  3. @concurrent 用于将你的 CPU 密集型工作 移出主线程——仅在 Instruments 显示存在挂起之后。
  4. actor 用于将 状态 移出主 Actor——仅当太多主 Actor 状态强制任务不断跳回时。

首先打开正确的构建设置。 在每个项目中启用 Approachable Concurrency。对于应用模块和 UI 相关模块,还将 Default Actor Isolation 设置为 MainActor——这是 Xcode 26 中新应用项目的默认设置,它删除了你的大多数 @MainActor 标注。在包中:swiftSettings: [.defaultIsolation(MainActor.self)]。不要为通用库设置主 Actor 默认隔离——库应该提供 nonisolated API 并让客户端决定工作在哪里运行。

发生变化的规则

在 Swift 6.2 中,将函数标记为 async 并不会将其移出当前 Actor。 它会在调用它的地方运行。这正是“最自然的编码方式”默认无数据竞争的原因。

  • @concurrent——总是切换到并发线程池。将其用于你的 CPU 密集型工作。
  • nonisolated——在调用它的任何地方运行。这是库 API 的正确默认值,因为由调用者决定。对类型使用 nonisolated 会使其所有成员都变为非隔离(Swift 6.1+)。
  • 两者都不用——留在调用者的 Actor 上。
nonisolated struct PhotoProcessor {          // 与主 Actor 解耦
  @concurrent                                // 保证在后台运行
  func process(_ data: Data) async -> ProcessedPhoto {
    async let sticker = extractSticker(data)  // 两个独立任务,并行执行
    async let colors  = extractColors(data)
    return await ProcessedPhoto(sticker: sticker, colors: colors)
  }
}
  • 在卸载工作之前先进行性能分析。 使用 Instruments(Time Profiler、hangs)。如果可以在没有并发的情况下使代码更快,始终优先这样做。并发具有实际成本——任务分配、调度和推理。
  • 不要为琐碎工作生成任务。 一个读取 UserDefaults 值的子任务成本高于其节省。
  • 每个端到端操作一个任务。 必须按顺序进行的工作放在 一个 任务中;独立的操作分别设置任务,以便运行时可以交织执行它们。
  • await 是一个挂起点,它会破坏原子性。 状态在挂起期间可能发生变化,并且你可能在不同的线程上恢复。在每个 await 之后重新检查假设。永远不要在持有锁的情况下跨越 await 执行。永远不要依赖跨 await 的线程本地存储。

Actor 的可重入性

Actor 保证互斥,而不是事务。在同一 Actor 上的两个 await 之间,其他工作会运行。

  • 在同步方法中修改 Actor 状态。 Actor 上的同步代码不间断地执行完毕——这就是你的事务边界。
  • 保持异步 Actor 方法精简,由同步事务操作组成,并在每个 await 处使 Actor 处于一致状态。
  • 经典 bug:检查缓存 → await 下载 → 写入缓存。两个任务都未命中,都下载,第二个覆盖第一个。在 await 之后重新检查,或者对正在进行的任务去重。
  • Actor 不是 FIFO 的。 它们首先运行最高优先级的任务,正是为了避免优先级反转。如果需要排序,请使用任务(从头到尾连续执行)或 AsyncStream,而不是 Actor。

4. Sendable 与数据共享

Sendable 标记一个类型安全地跨隔离域共享。编译器在每个任务和 Actor 边界处检查它。

  • 值类型在其存储是 Sendable 时自动成为 Sendable——对于非公共类型自动推断。公共类型永远不会自动推断可发送性:将公共类型标记为 Sendable 是对客户端的承诺,所以 Swift 要求你明确写出。
  • Actor 和 @MainActor 类隐式是 Sendable,因为它们的状态是隔离的。
  • 大多数模型类既不应是 @MainActor 也不应 Sendable。 有目的地保持它们非 Sendable——这可以防止一半模型在主线程上被修改,而另一半在后台被修改。如果它们需要离开主 Actor,让它们变成 nonisolated,而不是 Sendable。
  • 你仍然可以在域之间 发送 一个非 Sendable 对象,只要发送者停止使用它。在移交之前完成所有修改;之后触摸它是错误的。
  • 闭包也会捕获状态。仅当函数类型确实跨越域时才标记为 @Sendable。
  • @unchecked Sendable 是一个编译器无法检查的承诺。 将其保留给具有真正内部同步的类型(Mutex、锁)。同样,对全局变量使用 nonisolated(unsafe) 是最后的手段,而不是警告沉默器。

当你遇到数据竞争错误时,按此列表逐步排查:

  1. 不要共享它。 将共享对象移动到局部变量中,使每个并发任务都有自己的实例。(这是绝大多数真实错误的修复方式。)
  2. 将其变为 Sendable 值类型,这样“共享”实际上就是复制。
  3. 将其隔离到 Actor——主 Actor 或你自己的 Actor。
  4. 然后才考虑使用 Synchronization 模块中的 Mutex/Atomic(将它们存储在 let 属性中),或 @unchecked Sendable。

全局变量和静态变量是错误最常见的来源。 按优先级:使其变为 let;将其放在 @MainActor 上;将其包装在 Mutex 中;最后使用 nonisolated(unsafe)。注意 Swift 中的全局变量是惰性初始化且原子化的——与 C 不同。

桥接旧的回调 API: 如果你拥有委托协议,则用 @MainActor 注解它。如果你不拥有,将方法标记为 nonisolated 并使用 MainActor.assumeIsolated { }——它会断言而不是跳转,所以它会大声崩溃而不是静默竞争。符合性上的 @preconcurrency 是相同含义的简写。使用 @preconcurrency import 来临时沉默来自尚未迁移模块的可发送性警告;一旦迁移完成,警告会正确地重新出现。


5. 结构化并发

始终优先使用结构化任务。

结构化任务(async let、任务组)的作用域像局部变量一样:它们无法存活于代码块之外,会自动等待,并通过任务树继承取消、优先级和任务局部值。非结构化任务(Task { }、Task.detached)不会自动提供这些特性。

  • async let 用于固定、静态已知数量的并发子任务。
  • withTaskGroup 当数量是动态时使用。任务组遵循 AsyncSequence——在结果到达时迭代它们。当子任务不返回任何内容时使用 withDiscardingTaskGroup:它会立即释放每个子任务的资源,并在第一个错误时取消兄弟任务。
  • Task { } 仅当工作的生命周期不适合作用域时使用——响应委托回调、按钮点击、视图出现。它继承 Actor 隔离和优先级;你必须自己管理取消。
  • Task.detached 几乎从不使用。它不继承任何东西——不继承隔离、优先级、任务局部值。如果需要分离的根任务,请在其内部放置一个任务组,而不是反复分离。

取消是协作式的。 取消设置一个标志;它不会停止任何东西。在开始昂贵工作之前检查 Task.isCancelled 或 try Task.checkCancellation(),在同步辅助方法中也一样。对于正在挂起而非运行的工作(AsyncSequence 的 next()),使用 withTaskCancellationHandler——并记住处理程序会立即运行并与主体并发,因此它接触的状态需要真正的同步(原子量或锁,而不是 Actor——你无法保证 Actor 上的顺序)。

限制你的并发。 不要对无界列表中的每个项目都扇出一个子任务。启动 N 个子任务,然后添加一个 n…

…(原文截断)

Individual skills in this repo

This repo contains 13 individual skills — each has its own dedicated page.

CharbelElBateh/personal-website

Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use `animate`.

CharbelElBateh/personal-website

Build an animation from scratch, making the decisions in the order that determines whether it feels right — should it animate at all, what purpose, which tool, which properties, which curve and duration, how it interrupts, how it exits. Writes the implementation. Use when asked to animate something, add motion, make a component feel alive, or build a transition. For critiquing existing motion use review-animations; for auditing a whole codebase use improve-animations.

CharbelElBateh/personal-website

Reverse-lookup glossary that turns a vague description of a web animation or motion effect into its exact term ("the bouncy thing when a popover opens" → Pop in; "the iOS rubber-band scroll" → Rubber-banding). Use when the user asks "what's it called when…", or describes a motion effect without knowing its name and wants the right word to prompt an AI or designer with. For naming an effect, not designing or building one.

CharbelElBateh/personal-website

Apple's approach to interface design and fluid, physical motion, translated for the web. Use when building or reviewing gesture-driven UI, spring animations, drag/swipe/sheet interactions, momentum and interruptible transitions, translucent materials and depth, typography (optical sizing, tracking, leading), reduced-motion, or the design foundations (feedback, spatial consistency, restraint) behind Apple-style interfaces.

CharbelElBateh/personal-website

Guide to Sonner, the React toast library — install and wire up the Toaster, pick the right toast() call, promise and loading toasts, updating, dismissing and persisting toasts, styling, theming and icons, positioning and multiple toasters. Use when working with Sonner or troubleshooting it — toasts that don't appear, appear twice, lose their styles, ignore Tailwind classes, sit behind a modal, or don't follow dark mode.

CharbelElBateh/personal-website

Try to break a piece of UI by feeding it worst-case data — long names, unbreakable emails, one-letter names, missing fields, huge counts, zero items, long labels, non-Latin text, emoji, extreme numbers — then render it behind a "Demo data / Worst case" toggle and report everything that broke, with the fix for each. Use when the user asks to stress-test, break, or find edge cases in a component or screen, or to "try the worst case". For visual design critique use emil-design-eng; for motion use review-animations.

CharbelElBateh/personal-website

This skill encodes Emil Kowalski's philosophy on UI polish, component design, animation decisions, and the invisible details that make software feel great.

CharbelElBateh/personal-website

Search a codebase or UI for places that don't animate but should, and reject everything that shouldn't. Read-only; it proposes motion with exact values, it does not implement it. Use when the user asks "what could be animated here?" or wants to "make this feel more alive". For fixing existing animations, use improve-animations or review-animations instead.

CharbelElBateh/personal-website

Survey a codebase's animation and motion code as a senior motion advisor, then produce a prioritized audit and self-contained implementation plans for other agents (or cheaper models) to execute. Read-only on source code — it plans improvements, it does not apply them. Use when the user asks to "improve the animations", "audit the motion", "make this app feel better", or wants a roadmap of animation fixes rather than a review of a single diff.

CharbelElBateh/personal-website

Make a web app feel native on a phone — the small CSS and meta-tag fixes that separate "a website in a browser" from something that feels installed. Covers sticky hover states, tap highlight flashes, the 100vh bug, inputs that zoom the page, laggy taps, pull-to-refresh hijacking scroll, content under the notch, long-press selecting button text, carousels that scroll the wrong way, mismatched status bars, and the rule that you test on real hardware. Use when a web app is being built for or reviewed on mobile, when something "works in Chrome but feels wrong on my phone", when building a PWA, a bottom sheet, a carousel, a full-screen layout, or any touch interaction. For motion itself use animate; for React Native use animate-expo.

CharbelElBateh/personal-website

Pick the right library for a given frontend task from a curated, opinionated list — numbers, OTP inputs, charts, command menus, virtualization, drag and drop, toasts, state, styling, and more. Only runs when explicitly invoked; it does not trigger on its own.

CharbelElBateh/personal-website

Build multiple genuinely different versions of a UI piece you describe, rendered behind a visual picker so you can flip through them live and promote the one that feels right. Only runs when explicitly invoked; it does not trigger on its own.

CharbelElBateh/personal-website

Reviews animation and motion code against a high craft bar derived from Emil Kowalski's design engineering philosophy. Default to flagging; approval is earned.

相关技能