language-swiftlisted
Install: claude install-skill lugassawan/swe-workbench
# Swift
## Optionals
- `?` makes absence explicit in the type — `String?` vs `String`.
- `if let` / `guard let` unwrap safely. `guard` exits scope immediately — prefer it for preconditions.
- `??` provides a default for `nil`. **Never force-unwrap (`!`) in production** unless the nil case is a programmer error that should crash loudly.
```swift
guard let email = user.email else { return }
let display = nickname ?? username
```
## Value vs reference types
- Default to `struct` — value semantics, copy-on-write, no shared-mutation bugs.
- Use `class` only when identity matters (reference equality, inheritance), or when Objective-C interop requires it.
- Use `actor` to encapsulate mutable state that must be safe to access from multiple async tasks.
```swift
actor Counter {
private var count = 0
func increment() { count += 1 }
func value() -> Int { count }
}
```
## Protocols and protocol-oriented design
- Model capabilities as protocols, not class hierarchies. `Hashable`, `Codable`, `Identifiable` are the idiom.
- Extension methods add behavior without subclassing.
- `some Protocol` (opaque return type) keeps the concrete type private while preserving type identity.
- `any Protocol` (existential) erases the type — use only when you need a heterogeneous collection.
```swift
protocol Fetchable { associatedtype Item; func fetch(id: String) async throws -> Item }
func loadFirst<F: Fetchable>(from source: F) async throws -> F.Item { try await source.fetch(id: "1") }
`