Loading...
Loading...
Expert Swift decisions Claude doesn't instinctively make: struct vs class trade-offs, @MainActor placement, async/await vs Combine selection, memory management pitfalls, and iOS-specific anti-patterns. Use when writing Swift code for iOS/tvOS apps, reviewing Swift architecture decisions, or debugging memory/concurrency issues. Trigger keywords: Swift, iOS, tvOS, actor, async, Sendable, retain cycle, memory leak, struct, class, protocol, generic
npx skill4agent add kaakati/rails-enterprise-dev swift-conventionsNeed shared mutable state across app?
├─ YES → Class (singleton pattern, session managers)
└─ NO
└─ Need inheritance hierarchy?
├─ YES → Class (UIKit subclasses, NSObject interop)
└─ NO
└─ Data model or value type?
├─ YES → Struct (User, Configuration, Point)
└─ NO → Consider what identity means
├─ Same instance matters → Class
└─ Same values matters → Structstruct[UIImage]Is this a one-shot operation? (fetch user, save file)
├─ YES → async/await (cleaner, better stack traces)
└─ NO → Is it a stream of values over time?
├─ YES
│ └─ Need transformations/combining?
│ ├─ Heavy transforms → Combine (map, filter, merge)
│ └─ Simple iteration → AsyncStream
└─ NO → Must support iOS 14?
├─ YES → Combine or callbacks
└─ NO → async/await with continuationcombineLatestmergedebounceIs every public method UI-related?
├─ YES → @MainActor on class/struct
└─ NO
└─ Does it manage UI state? (@Published, bindings)
├─ YES → @MainActor on class, nonisolated for non-UI methods
└─ NO
└─ Only some methods touch UI?
├─ YES → @MainActor on specific methods
└─ NO → No @MainActor needed@PublishedNumber of concurrent operations known at compile time?
├─ YES (2-5 fixed operations) → async let
│ Example: async let user = fetchUser()
│ async let posts = fetchPosts()
│
└─ NO (dynamic count, array of IDs) → TaskGroup
Example: for id in userIds { group.addTask { ... } }async letself// ❌ Retain cycle — ViewModel never deallocates
class ViewModel {
var onUpdate: (() -> Void)?
func setup() {
onUpdate = { self.refresh() } // self → onUpdate → self
}
}
// ✅ Break with weak capture
onUpdate = { [weak self] in self?.refresh() }unownedweakunowned// ❌ Timer retains target — object never deallocates
timer = Timer.scheduledTimer(target: self, selector: #selector(tick), ...)
// ✅ Block-based with weak capture + invalidate in deinit
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
self?.tick()
}
deinit { timer?.invalidate() }@Published// ❌ Undefined behavior — may work sometimes, crash others
Task.detached {
viewModel.isLoading = false // Background thread!
}
// ✅ Explicit MainActor
Task { @MainActor in
viewModel.isLoading = false
}Task { }// ❌ Task inherits actor context — may block UI
func buttonTapped() {
Task { await heavyOperation() } // Runs on MainActor!
}
// ✅ Explicit detachment for background work
func buttonTapped() {
Task.detached(priority: .userInitiated) {
await heavyOperation()
}
}Task.cancel()Task.isCancelledtry Task.checkCancellation()@IBOutletURL(string: "https://known-valid.com")!fatalErrorvar user: User!@IBOutletAnyObjectweak// ❌ Unnecessarily restricts to classes
protocol DataProvider: AnyObject {
func fetchData() -> Data
}
// ✅ Only require AnyObject for delegates that need weak reference
protocol ViewModelDelegate: AnyObject { // Needed for weak var delegate
func viewModelDidUpdate()
}// ❌ Dangerous — conformers might not override
protocol Validator {
func validate() -> Bool
}
extension Validator {
func validate() -> Bool { true } // Silent "always valid"
}
// ✅ Make requirement obvious or use different name
extension Validator {
func isAlwaysValid() -> Bool { true } // Clear this is a default
}// ✅ Protocol-based for testability
protocol UserServiceProtocol {
func fetchUser(id: String) async throws -> User
}
@MainActor
final class UserViewModel: ObservableObject {
@Published private(set) var user: User?
@Published private(set) var error: Error?
private let userService: UserServiceProtocol
init(userService: UserServiceProtocol = UserService()) {
self.userService = userService
}
}| Wrapper | Use When | Memory Behavior |
|---|---|---|
| View-local primitive/value types | View-owned, recreated on parent rebuild |
| View creates and owns the ObservableObject | Created once, survives view rebuilds |
| View receives ObservableObject from parent | Not owned, may be recreated |
| Shared across view hierarchy | Must be injected by ancestor |
| Two-way connection to parent's state | Reference to parent's storage |
@ObservedObject// Domain-specific errors with recovery info
enum UserError: LocalizedError {
case notFound(userId: String)
case unauthorized
case networkFailure(underlying: Error)
var errorDescription: String? {
switch self {
case .notFound(let id): return "User \(id) not found"
case .unauthorized: return "Please log in again"
case .networkFailure: return "Connection failed"
}
}
var recoverySuggestion: String? {
switch self {
case .notFound: return "Check the user ID and try again"
case .unauthorized: return "Your session expired"
case .networkFailure: return "Check your internet connection"
}
}
}// ✅ COW works — array copied only on mutation
var a = [1, 2, 3]
var b = a // No copy yet
b.append(4) // Now b gets its own copy
// ❌ COW broken — class inside struct
struct Container {
var items: NSMutableArray // Reference type!
}
var c1 = Container(items: NSMutableArray())
var c2 = c1 // Both point to same NSMutableArray
c2.items.add(1) // Mutates c1.items too!// lazy: Computed ONCE, stored
lazy var dateFormatter: DateFormatter = {
let f = DateFormatter()
f.dateStyle = .medium
return f
}()
// computed: Computed EVERY access
var formattedDate: String {
dateFormatter.string(from: date) // Cheap, uses cached formatter
}lazy// ❌ O(n) for each concatenation in loop
var result = ""
for item in items {
result += item.description // Creates new String each time
}
// ✅ O(n) total
var result = ""
result.reserveCapacity(estimatedLength)
for item in items {
result.append(item.description)
}
// ✅ Best for joining
let result = items.map(\.description).joined(separator: ", ")| Level | Use When |
|---|---|
| Implementation detail within declaration |
| Shared between types in same file (rare) |
| Module-internal, app code default |
| Same package, different module (Swift 5.9+) |
| Framework API, readable outside module |
| Framework API, subclassable outside module |
privatePascalCaseUserViewModelNetworkErrorPascalCase-able/-iblecamelCasefetchUser()configure(with:)is/has/should/canisLoadinghasContentmakemakeUserViewModel()