swift
它能做什么
这份指南教你如何编写更高效、更正确的 Swift 代码,遵循该语言的最佳实践。它展示了如何有效使用“可选类型”(Optionals)和“并发”(Concurrency)等特性。
适用场景
- ✓当你想编写更简洁、更安全的 Swift 代码时。
- ✓当你想学习处理“可能有值,也可能没有值”的推荐方式(可选类型)时。
- ✓当你需要处理同时进行的任务(并发)时。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/swift/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我怎样才能确保 Swift 代码正确处理可能不存在的值?”
每周 5 个新技能,1 分钟读完。
工作原理
这份指南通过对比“糟糕”和“良好”的代码示例来说明最佳实践,重点讲解如何更智能地使用 Swift 的语言工具,避免常见错误。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Swift: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for swift.
Table of Contents
- Optionals
- Collections & Functional Transforms
- Value vs Reference Types
- Error Handling
- Concurrency
- Protocol-Oriented Design
- Anti-patterns specific to Swift
1. Optionals {#optionals}
// ❌ Force unwrap
let name = user.name!
// ✅ — guard or if-let
guard let name = user.name else { return }
// ❌ Nested if-let pyramid
if let user = fetchUser() {
if let address = user.address {
if let city = address.city {
display(city)
}
}
}
// ✅ — chained optional binding
if let city = fetchUser()?.address?.city {
display(city)
}
// or guard-let for early exit
guard let city = fetchUser()?.address?.city else { return }
display(city)
// ❌ Ternary for default
let name = user.name != nil ? user.name! : "Unknown"
// ✅
let name = user.name ?? "Unknown"
// ❌ Optional map when if-let is clearer for side effects
user.name.map { display($0) }
// ✅ — map for transforms, if-let for side effects
let upper = user.name.map { $0.uppercased() }
if let name = user.name { display(name) }
2. Collections & Functional Transforms {#collections}
// ❌ Imperative filter + map
var result: [String] = []
for item in items {
if item.isActive { result.append(item.name.uppercased()) }
}
// ✅
let result = items
.filter(\.isActive)
.map { $0.name.uppercased() }
// ❌ Manual dictionary construction
var dict: [String: User] = [:]
for user in users { dict[user.id] = user }
// ✅
let dict = Dictionary(uniqueKeysWithValues: users.map { ($0.id, $0) })
// or with possible duplicates:
let dict = Dictionary(grouping: users, by: \.department)
// ❌ Checking isEmpty then accessing first
if !items.isEmpty { process(items[0]) }
// ✅
if let first = items.first { process(first) }
// ❌ Index-based loop
for i in 0..<items.count { process(items[i]) }
// ✅
for item in items { process(item) }
// with index:
for (i, item) in items.enumerated() { process(i, item) }
Use key paths (\.isActive) as closure shorthand where supported.
3. Value vs Reference Types {#value-types}
// ❌ Class for plain data (reference semantics where value semantics suffice)
class Point {
var x: Double
var y: Double
init(x: Double, y: Double) { self.x = x; self.y = y }
}
// ✅
struct Point { var x, y: Double }
// ❌ Large struct copied repeatedly (performance hit)
struct HugeData { var buffer: [UInt8] /* thousands of elements */ }
func process(_ data: HugeData) { ... } // copies entire buffer
// ✅ — use class or pass inout for mutation
func process(_ data: inout HugeData) { ... }
// or use copy-on-write wrapper for large value types
Default to struct. Use class when you need identity, inheritance, or reference semantics.
4. Error Handling {#errors}
// ❌ Using optionals to mask errors
func parse(_ input: String) -> Data? { ... } // caller doesn't know why it failed
// ✅
func parse(_ input: String) throws -> Data { ... }
// ❌ try! in production code
let data = try! JSONDecoder().decode(User.self, from: jsonData)
// ✅
do {
let data = try JSONDecoder().decode(User.self, from: jsonData)
} catch {
logger.error("decode failed: \(error)")
throw AppError.decodingFailed(underlying: error)
}
// ❌ Generic Error type
enum AppError: Error { case generic(String) }
// ✅ — specific, actionable error cases
enum AppError: Error {
case networkUnreachable
case invalidInput(field: String, reason: String)
case unauthorized
}
// ❌ Catching all errors and ignoring
do { try riskyOperation() } catch { }
// ✅
do {
try riskyOperation()
} catch let error as NetworkError {
handleNetworkError(error)
} catch {
throw error // rethrow unknown
}
5. Concurrency {#concurrency}
// ❌ Callback-based async (pyramid of doom)
fetchUser { user in
fetchPosts(for: user) { posts in
fetchComments(for: posts.first!) { comments in
display(comments)
}
}
}
// ✅ (Swift 5.5+)
let user = try await fetchUser()
let posts = try await fetchPosts(for: user)
…
常见问题
Swift 中的“Optionals”是什么?
“Optionals”是 Swift 中的一种机制,用来表示一个变量可能保存某个值,也可能什么都不保存(即 `nil`)。指南会讲解如何安全地处理这种情况。
Swift 中的“并发”(Concurrency)是什么?
“并发”指的是同时执行多个任务的能力。指南会讲解如何在 Swift 中利用最新的工具高效地做到这一点。
为什么在 Swift 中要用 `struct` 而不是 `class`?
一般来说,Swift 中处理简单数据时更推荐使用 `struct`,因为它采用拷贝方式工作(值语义),这样往往更安全、更可预测。只有当你需要共享数据或需要对象身份时,才会使用 `class`。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5900
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。