swift-best-practices by secondsky/claude-skills
npx skills add https://github.com/secondsky/claude-skills --skill swift-best-practices应用现代 Swift 开发最佳实践,重点关注 Swift 6+ 特性、并发安全性、API 设计原则以及针对 macOS 15.7+ 的 iOS 和 macOS 项目的代码质量指南。
在以下情况下使用此技能:
此技能与 SwiftLens MCP 服务器 相辅相成,用于语义级的 Swift 代码分析。
SwiftLens 提供:
此技能提供:
Claude Code CLI 设置:
在你的 Swift 项目中创建 .claude/mcps/swiftlens.json:
{
"mcpServers": {
"swiftlens": {
"description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",
"command": "uvx",
"args": ["swiftlens"]
}
}
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
⚠️ 注意:这是 Claude Code 配置(非 Claude Desktop)。完整的设置指南、全部 15 个工具、索引构建和使用示例,请参阅 references/swiftlens-mcp-claude-code.md。
工作流程:SwiftLens 提供 运行时分析(代码在做什么),此技能提供 设计专业知识(代码应该做什么)。
var greeting = "Hello" 而非 var string = "Hello"Swift 6 默认启用完整的并发检查,并采用基于区域的隔离(SE-0414)。编译器现在可以证明代码安全性,消除了许多误报,同时能在编译时捕获真正的并发问题。
关键理解:
@MainActor 确保与 UI 相关的代码在主线程上执行Sendable// 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
}
// 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 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
}
}
async - 异步调用约定有开销DispatchSemaphore 与 async/await 一起使用 - 存在死锁风险Task.checkCancellation()UpperCamelCaselowerCamelCase-able、-ible、-ing(Equatable、ProgressReporting)make 开头(x.makeIterator())x.sort() / x.sorted())x.distance(to: y))x.append(y)、x.sort())min(number1, number2)Int64(someUInt32)x.removeBoxes(havingLength: 12)属性包装器不再自动推断 Actor 隔离。
@MainActor
struct LogInView: View {
@StateObject private var model = ViewModel()
}
static let config = Config() // Constant - OK
@MainActor static var state = State() // Actor-isolated - OK
nonisolated(unsafe) var cache = [String: Data]() // Unsafe - use with caution
@UIApplicationMain/@NSApplicationMain 已弃用(使用 @main)any// 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
}
关键区别:
deprecated - 警告,允许使用obsoleted - 从特定版本起报错unavailable - 错误,完全阻止使用@MainActor,可变状态用 actors)count(where:) 而非 filter().countInlineArraySendable 一致性需要深入信息时加载的详细参考资料:
@available 属性用法、弃用策略和平台版本管理当需要超出上述核心指南的详细信息时,请加载这些参考资料。
#available 进行运行时平台检测@available 进行 API 可用性标记每周安装数
82
仓库
GitHub 星标数
90
首次出现
2026年1月25日
安全审计
安装于
claude-code72
gemini-cli69
codex68
cursor68
opencode68
github-copilot64
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+.
Use this skill when:
This skill complements SwiftLens MCP server for semantic-level Swift code analysis.
What SwiftLens Provides:
What This Skill Provides:
Setup for Claude Code CLI:
Create .claude/mcps/swiftlens.json in your Swift project:
{
"mcpServers": {
"swiftlens": {
"description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",
"command": "uvx",
"args": ["swiftlens"]
}
}
}
⚠️ Note : This is Claude Code configuration (not Claude Desktop). See references/swiftlens-mcp-claude-code.md for complete setup guide, all 15 tools, index building, and usage examples.
Workflow : SwiftLens provides runtime analysis (what the code is doing), this skill provides design expertise (what the code should be doing).
var greeting = "Hello" not var string = "Hello"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:
@MainActor ensures UI-related code executes on the main threadSendable// 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
}
// 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 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
}
}
async unnecessarily - async calling convention has overheadDispatchSemaphore with async/await - risk of deadlockTask.checkCancellation()UpperCamelCaselowerCamelCase-able, -ible, -ing suffixes (Equatable, ProgressReporting)make (x.makeIterator())x.sort() / x.sorted())x.distance(to: y))x.append(y), x.sort())min(number1, number2)Int64(someUInt32)x.removeBoxes(havingLength: 12)Property wrappers no longer infer actor isolation automatically.
@MainActor
struct LogInView: View {
@StateObject private var model = ViewModel()
}
static let config = Config() // Constant - OK
@MainActor static var state = State() // Actor-isolated - OK
nonisolated(unsafe) var cache = [String: Data]() // Unsafe - use with caution
@UIApplicationMain/@NSApplicationMain deprecated (use @main)any required for existential types// 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 usageobsoleted - Error from specific versionunavailable - Error, completely prevents usage@MainActor for UI, actors for mutable state)count(where:) over filter().countInlineArray for fixed-size, performance-critical dataSendable conformancesDetailed reference material to load when in-depth information is needed:
@available attribute usage, deprecation strategies, and platform version managementLoad these references when detailed information is needed beyond the core guidelines provided above.
#available for runtime platform detection@available for API availability markingWeekly Installs
82
Repository
GitHub Stars
90
First Seen
Jan 25, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code72
gemini-cli69
codex68
cursor68
opencode68
github-copilot64
TorchTitan:PyTorch原生分布式大语言模型预训练平台,支持4D并行与H100 GPU加速
69 周安装
screenshot 截图技能:跨平台桌面截图工具,支持macOS/Linux权限管理与多模式捕获
69 周安装
tmux进程管理最佳实践:交互式Shell初始化、会话命名与生命周期管理
69 周安装
Git Rebase Sync:安全同步分支的Git变基工具,解决冲突与备份
69 周安装
LinkedIn自动化工具 - Claude Code专属,自然对话拓展人脉,避免垃圾信息
69 周安装
实验流水线框架:4阶段科研实验执行与消融研究方法论 | EvoScientist
69 周安装