swift-style
Swift Style Guide
Code style conventions for clean, readable Swift code.
Core Principles
Clarity > Brevity > Consistency
Code should compile without warnings.
Naming
UpperCamelCase— Types, protocolslowerCamelCase— Everything else- Clarity at call site
- No abbreviations except universal (URL, ID)
// Preferred
let maximumWidgetCount = 100
func fetchUser(byID id: String) -> User
Golden Path
Left-hand margin is the happy path. Don't nest if statements.
// Preferred
func process(value: Int?) throws -> Result {
guard let value = value else {
throw ProcessError.nilValue
}
guard value > 0 else {
throw ProcessError.invalidValue
}
return compute(value)
}
Code Organization
Use extensions and MARK comments:
class MyViewController: UIViewController {
// Core implementation
}
// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource { }
Spacing
- Braces open on same line, close on new line
- One blank line between methods
- Colon: no space before, one space after
Self
Avoid self unless required by compiler.
// Preferred
func configure() {
backgroundColor = .systemBackground
}
Computed Properties
Omit get for read-only:
var diameter: Double {
radius * 2
}
Closures
Trailing closure only for single closure parameter.
Type Inference
Let compiler infer when clear. For empty collections, use type annotation:
var names: [String] = []
Syntactic Sugar
// Preferred
var items: [String]
var cache: [String: Int]
var name: String?
Access Control
privateoverfileprivate- Don't add
internal(it's the default) - Access control as leading specifier
Memory Management
resource.request().onComplete { [weak self] response in
guard let self else { return }
self.updateModel(response)
}
Comments
- Explain why, not what
- Use
//or///, avoid/* */ - Keep up-to-date or delete
Constants
Use case-less enum for namespacing:
enum Math {
static let pi = 3.14159
}
Common Mistakes
-
Abbreviations beyond URL, ID, UUID — Abbreviations like
cfg,mgr,ctx,deschurt readability. Spell them out:configuration,manager,context,description. The three exceptions are URL, ID, UUID. -
Nested guard/if statements — Deep nesting makes code hard to follow. Use early returns and guards to keep the happy path left-aligned.
-
Inconsistent self usage — Either always omit
self(preferred) or always use it. Mixing makes code scanning harder and confuses capture semantics. -
Overly generic type names —
Manager,Handler,Helper,Coordinatorare too vague. Names should explain responsibility:PaymentProcessor,EventDispatcher,ImageCache,NavigationCoordinator. -
Implied access control — Don't skip access control. Explicit
private,publichelps future maintainers understand module boundaries.internalis default, so omit it.
More from hocgin/agent-skills
swift-private-bundle
Use when working with private Swift Package Manager dependencies from github.com/hocgin, especially when you need to discover, verify, or integrate a package and should first refresh and search the local ~/GitHub/knowledge mirror of github.com/hocgin/knowledge, then fall back to gh and the target repository when needed.
6swift-sqlite-data
Use when working with SQLiteData library (@Table, @FetchAll, @FetchOne macros) for SQLite persistence, queries, writes, migrations, or CloudKit private database sync.
6article-writer
AI驱动的智能写作系统,专注于创作高质量、低AI检测率的文章内容
5wrangler
Cloudflare Workers CLI for deploying, developing, and managing Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines, and Secrets Store. Load before running wrangler commands to ensure correct syntax and best practices.
4xlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like \"the xlsx in my downloads\") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.
4browser-extension-builder
Expert in building browser extensions that solve real problems - Chrome, Firefox, and cross-browser extensions. Covers extension architecture, manifest v3, content scripts, popup UIs, monetization strategies, and Chrome Web Store publishing. Use when: browser extension, chrome extension, firefox addon, extension, manifest v3.
4