swift-development
БесплатноБез исполняемых скриптовНе проверенYou MUST activate this skill when working on Swift projects
от sammcj★ 175 звёзд на GitHubОб этом скилле
Swift Best Practices Skill
Overview
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+.
Core Guidelines
Fundamental Principles
- Clarity at point of use is paramount - evaluate designs by examining use cases, not just declarations
- Clarity over brevity - compact code comes from the type system, not minimal characters
- Write documentation for every public declaration - if you can't describe functionality simply, the API may be poorly designed
- Name by role, not type -
var greeting = "Hello"notvar string = "Hello" - Favour elegance through simplicity - avoid over-engineering unless complexity genuinely warrants it
Swift 6 Concurrency Model
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:
- Async ≠ background - async functions can suspend but don't automatically run on background threads
- Actors protect mutable shared state through automatic synchronisation
@MainActorensures UI-related code executes on the main thread- Global actor-isolated types are automatically
Sendable
Essential Patterns
Async/Await
// 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
}
MainActor for UI Code
// 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 Isolation
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
}
}
Common Pitfalls to Avoid
- Don't mark functions as
asyncunnecessarily - async calling convention has overhead - Never use
DispatchSemaphorewith async/await - risk of deadlock - Don't create stateless actors - use non-isolated async functions instead
- Avoid split isolation - don't mix isolation domains within one type
- Check task cancellation - long operations must check
Task.checkCancellation() - Don't assume async means background - explicitly move work to background if needed
- Avoid excessive context switching - group operations within same isolation domain
AppKit Gotchas
Menu-bar app windows open behind everything / hide on click-away. Two separate causes, usually hit together:
.accessoryactivation policy means the app is never brought forward when a window opens.- SwiftUI's
Settingsscene is anNSPanel, which in an accessory app defaults tohidesOnDeactivate = true.
Fix both: switch to .regular while the window is open, clear hidesOnDeactivate, then revert on NSWindow.willCloseNotification.
NSApp.setActivationPolicy(.regular)
NSApp.activate()
openSettings()
DispatchQueue.main.async { // window does not exist until SwiftUI opens it
guard let w = NSApp.windows.first(where: {
$0.identifier?.rawValue.hasPrefix("com_apple_SwiftUI_Settings") == true }) else { return }
w.hidesOnDeactivate = false
w.makeKeyAndOrderFront(nil)
w.orderFrontRegardless()
}
// On willCloseNotification: NSApp.setActivationPolicy(.accessory)
Cost: a Dock icon while the window is open. SettingsLink cannot do this - it has no action hook, so use @Environment(\.openSettings).
JSONEncoder.dateEncodingStrategy = .iso8601 truncates to whole seconds. Silently breaks any sub-second timing logic. Use .custom with ISO8601DateFormatter + .withFractionalSeconds.
API Design Quick Reference
Naming Conventions
- Types/protocols:
UpperCamelCase - Everything else:
lowerCamelCase - Protocols describing capabilities:
-able,-ible,-ingsuffixes (Equatable,ProgressReporting) - Factory methods: Begin with
make(x.makeIterator()) - Mutating pairs: imperative vs past participle (
x.sort()/x.sorted())
Method Naming by Side Effects
Установить swift-development в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл swift-development?
You MUST activate this skill when working on Swift projects
Как установить скилл swift-development?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swift-development запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic