Communitygithub.com

CharbelElBateh/personal-website

如何以現代 Swift 正確撰寫程式碼 — 包含值類型建模、Swift 6 資料競賽安全性、易於理解的並行性(@concurrent、MainActor 預設、Actor、Task Groups)、協定與泛型(some vs any)、API 設計、效能與 ARC、Swift Testing、巨集,以及代理程式尚不熟悉的現代語言功能。在撰寫、審查或遷移 Swift 程式碼時使用,或在需要修復並行錯誤、無回應、資料競賽、記憶體循環或效能問題時使用。

personal-website 是什麼?

這個技能提供一份深入且實用的現代 Swift 開發指南,重點在於引導開發者與 AI 代理程式以符合語言設計理念的方式撰寫 Swift 程式碼。它涵蓋從基礎的值類型優先(struct/enum),到 Swift 6 的並行模型(包含 @concurrent、MainActor 預設、Actor 與 Task Groups)以及 Sendable 協定的正確運用。技能也深入探討協定與泛型(some vs any)、API 設計原則、效能與 ARC 記憶體管理、Swift Testing 以及巨集等進階主題。其核心哲學是「漸進式揭露」:從最簡單、靜態、單執行緒的方案開始,只在有明確理由時才引入動態性、並行性或參考語意。這個技能特別有價值,因為它揭示了 AI 代理程式常犯的 Swift 並行模型誤解(例如 async 函數不會自動切換執行緒),並提供清晰、逐步的指導方針。對於任何使用 Swift 6.3+ 的 iOS、macOS 或伺服器端開發者來說,這是一個不可或缺的參考資源,能幫助撰寫更安全、高效且易於維護的程式碼。

相容平台~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
執行main actor,同步效能分析顯示有無回應 → async → @concurrent → actor
記憶體Array, String效能分析顯示成本過高 → InlineArray, Span
安全性安全 APIC 互操作或經過測量的熱路徑 → Unsafe*

1. 使用值類型建模資料

值類型在 Swift 中是預設的,而不是特例。

  • 預設使用 struct 和 enum。只有在需要識別性、共享可變狀態、繼承或資源生命週期時,才使用 class。 一個視窗、一個資料庫連線、一個儲存在渲染引擎中的實體——那些具有識別性。一個 Point、一個 Drink、一個 Material 則沒有。
  • 預設使用 let;只有當你進行變異時才用 var。 這與 some 優先於 any、值優先於參考的紀律相同:從狹義開始,有原因才擴展。
  • 一個包含可變參考型別屬性的 struct,既不是值也不是參考。 複製會共享該物件;變異會在不同複本間洩漏。請保持被參考的型別不可變,只公開轉發給它的計算屬性,或使其成為 private 的儲存屬性並實作寫入時複製。
  • 寫入時複製是讓你同時擁有外部儲存和值語意的方法。 將一個 final class 包裝在 struct 中,並在變異前檢查 isKnownUniquelyReferenced(&storage);如果不是唯一參考,則先複製。這正是 Array、String 和 Dictionary 的運作方式。
  • Enum 是處理「一組固定事物」和互斥狀態的工具。 用一個 enum State 取代一堆可選儲存屬性(isSharing、selectedRows、shareTarget),可以使無效的組合無法被表示,並使狀態變更變成原子操作,而不是一系列你可能忘記完成的屬性寫入。
  • 組合值會產生一個值。 一個其儲存屬性都是值類型的 struct,會免費獲得值語意——這使得復原、差異比對和狀態恢復成為單一程式碼路徑,而不是每個屬性一條路徑。
struct Material {                       // 保留值語意
  var roughness: Double
  private var _texture: Texture         // 一個 class

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

不可複製型別(~Copyable)表達唯一擁有權:一個檔案描述子、一筆銀行轉帳、一個開啟的資源。抑制複製將「你不得執行此操作兩次」從斷言變成編譯錯誤,並使 struct 上的 deinit 變得有意義。將結束方法標記為 consuming,以便編譯器證明這是最後一次使用。參數擁有權變得明確:borrowing(唯讀,這是預設)、consuming(拿走它)、inout/mutating(暫時的寫入存取)。


2. 錯誤與可選值——讓失敗路徑可見

Swift 錯誤處理基於三點:錯誤來源必須被標記,以免造成意外;錯誤必須攜帶足夠的上下文以便採取行動;可回復的錯誤與程式設計師的錯誤不同。

  • 可回復 → throw。程式設計師錯誤 → precondition/fatalError。 一個失敗的網路呼叫會讓程式繼續執行。一個超出範圍的索引意味著程式碼有錯,必須在錯誤變成安全性問題之前停止。
  • 帶有關聯值的 Enum 是最佳的錯誤型別。 case duplicateFriend(String) 優於 case duplicateFriend——上下文是關鍵。
  • 使用 guard 處理錯誤條件,因為它強制使用退出路徑。使用 if let 處理一般的 unwrap。
  • Typed throws(throws(MyError))適用於內部函式、轉發錯誤的泛型程式碼以及受限環境,其中裝箱 any Error 成本過高。對於公開 API,無類型的 throws 保留了你在未來更改錯誤型別的自由。注意統一性:throws 就是 throws(any Error),而無拋出就是 throws(Never)——這正是 map 可以抽象化兩者的原因。
  • 只有在你能說明不變量的情況下才能 force-unwrap,並且更傾向於使用帶有訊息的失敗 #require/precondition,而不是單純的 !。

3. 並行性:在效能分析指出需要之前,保持單執行緒

這是代理程式最常搞錯的部分,因為模型在 Swift 6.2 中改變了。

每個應用程式都應從完全在主執行緒上執行開始。單執行緒程式碼可以走很遠,大多數應用程式從不需要離開它。

進階順序,依序進行。不要跳過步驟。

  1. 在 main actor 上保持單執行緒。 完全不需要並行性。對大多數應用程式來說就夠了。
  2. 使用 async/await 來隱藏延遲(網路、磁碟)。仍然沒有你自己的並行性——像 URLSession.data(from:) 這樣的 SDK API 會代表你卸載工作。
  3. 使用 @concurrent 將你自己的昂貴工作移出主執行緒——只有在 Instruments 顯示有無回應之後才這麼做。
  4. 使用 actor 將狀態移出 main actor——只有當太多 main actor 狀態導致任務必須不斷跳回時才這麼做。

首先開啟正確的建置設定。 在每個專案中啟用 Approachable Concurrency。對於應用程式模組和 UI 相關模組,也要將 Default Actor Isolation 設定為 MainActor——這是 Xcode 26 中新應用程式專案的預設值,它會刪除你大部分的 @MainActor 標註。在套件中:swiftSettings: [.defaultIsolation(MainActor.self)]。不要為通用用途的函式庫設定 main-actor-by-default——函式庫應該提供 nonisolated API,並讓用戶端決定工作在哪裡執行。

改變的規則

在 Swift 6.2 中,將函式標記為 async 並不會將其移出當前的 actor。 它會在呼叫它的地方執行。這就是使「最自然的程式碼」預設無資料競賽的原因。

  • @concurrent——總是切換到並行執行緒池。用它來處理你自己的 CPU 密集型工作。
  • nonisolated——在呼叫它的地方執行。這是函式庫 API 的正確預設值,因為由呼叫者決定。在型別上使用 nonisolated 會使其所有成員都變成非隔離(Swift 6.1+)。
  • 兩者都不用——保持在呼叫者的 actor 上。
nonisolated struct PhotoProcessor {          // 與 main 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 之後重新檢查假設。永遠不要在暫停期間持有鎖。永遠不要依賴跨暫停點的執行緒區域儲存。

Actor 可重入性

Actor 保證互斥,而不是交易。在同一個 actor 上的兩個 await 之間,其他工作會執行。

  • 在同步方法中變異 actor 狀態。 Actor 上的同步程式碼會不間斷地執行完成——那就是你的交易邊界。
  • 保持 async actor 方法精簡,由同步交易操作組成,並在每個 await 時讓 actor 保持一致的狀態。
  • 經典錯誤:檢查快取 → await 下載 → 寫入快取。兩個任務都錯失快取,都下載,第二個覆蓋了第一個。在 await 之後重新檢查,或對正在進行的工作進行去重。
  • Actor 不是 FIFO。 它們會先執行最高優先順序的工作,正是為了避免優先級反轉。如果你需要排序,請使用任務(從頭到尾執行)或 AsyncStream,而不是 actor。

4. Sendable 與共享資料

Sendable 標記一個型別可以安全地在隔離域之間共享。編譯器會在每個任務和 actor 邊界檢查它。

  • 當值類型的儲存是 Sendable 時,其本身也是 Sendable——對於非公開型別會自動推斷。公開型別永遠不會被推斷為 Sendable:將公開型別標記為 Sendable 是對你的用戶端的一個承諾,所以 Swift 要求你明確寫出。
  • Actor 和 @MainActor 類別是隱式的 Sendable,因為它們的狀態是隔離的。
  • 大多數模型類別既不應該是 @MainActor 也不應該是 Sendable。 故意讓它們保持 non-Sendable——這可以防止一半的模型在主執行緒上被變異,而另一半在背景被變異。如果它們需要離開 main actor,讓它們變成 nonisolated,而不是 Sendable。
  • 你仍然可以在域之間發送一個 non-Sendable 物件,只要發送者停止使用它。在交出物件之前完成所有變異;之後再觸碰它就會出錯。
  • Closure 也會捕獲狀態。只有在函式型別確實會跨域時,才將其標記為 @Sendable。
  • @unchecked Sendable 是一個編譯器無法檢查的承諾。 保留給具有真正內部同步機制(一個 Mutex、一個鎖)的型別。nonisolated(unsafe) 用於全域變數也是如此——這是最後的手段,而不是警告消除器。

當你遇到資料競賽錯誤時,依此清單向下處理:

  1. 不要共享它。 將共享物件移到區域變數中,這樣每個並行工作就會有自己的實例。(這是絕大多數真實錯誤的修正方法。)
  2. 讓它變成一個 Sendable 值類型,這樣「共享」實際上就是複製。
  3. 將其隔離到一個 actor 中——可以是 main actor,或你自己的 actor。
  4. 只有到此時才使用 Synchronization 模組中的 Mutex/Atomic(將它們儲存在 let 屬性中),或使用 @unchecked Sendable。

全域變數和靜態變數是最常見的錯誤來源。 優先順序:讓它變成 let;將它放在 @MainActor 上;將其包裝在 Mutex 中;最後才是 nonisolated(unsafe)。請注意 Swift 中的全域變數是惰性且原子地初始化——與 C 語言不同。

橋接舊的回呼 API: 如果你擁有委派協定,請用 @MainActor 標註它們。如果你沒有,請將方法標記為 nonisolated 並使用 MainActor.assumeIsolated { }——它會進行斷言而不是跳轉,因此它會大聲地陷入錯誤,而不是無聲地競爭。在遵從項上使用 @preconcurrency 是同樣事情的簡寫。使用 @preconcurrency import 來暫時壓制來自尚未遷移的模組的 sendability 警告;一旦該模組遷移,警告會正確地再次出現。


5. 結構化並行性

始終優先使用結構化任務。

結構化任務(async let、task groups)的作用域像區域變數一樣:它們不會比區塊活得久,會自動被 await,並透過任務樹繼承取消、優先順序和工作區域值。非結構化任務(Task { }、Task.detached)不會自動提供這些。

  • async let 用於固定、靜態已知數量的並行子任務。
  • withTaskGroup 當數量是動態時使用。Task groups 遵循 AsyncSequence——可以迭代取得的結果。當子任務不回傳任何東西時,使用 withDiscardingTaskGroup:它會立即釋放每個子任務的資源,並在第一個錯誤時取消兄弟任務。
  • Task { } 僅在工作生命週期不適合某個作用域時使用——例如回應委派回呼、按鈕點擊或視圖出現。它會繼承 actor 隔離和優先順序;你必須自己管理取消。
  • 幾乎不使用 Task.detached。它什麼都不繼承——不繼承隔離、不繼承優先順序、不繼承工作區域。如果你需要一個分離的根任務,與其反覆分離,不如在它內部放置一個 task group。

取消是協作式的。 取消只是設置一個標誌;它不會停止任何東西。在開始昂貴的工作之前,以及在同步輔助函式中,檢查 Task.isCancelled 或 try Task.checkCancellation()。對於已暫停而不是正在執行的工作(一個 AsyncSequence 的 next()),使用 withTaskCancellationHandler——並記住處理器會立即且與主體並行地執行,因此它觸及的狀態需要真正的同步機制(一個原子變數或鎖,而不是 actor——你無法保證 actor 上的順序)。

限制你的並行性。 不要為一個無界限列表中的每個項目都分散出一個子任務。先開始 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.

相關技能