Firebase Swift Best Practices Skill
Overview
Use this skill to implement robust, thread-safe, and performant Firebase integrations in modern Swift applications. This skill focuses on the intersection of Firebase SDKs and modern Swift features like @Observable, async/await, and Actor isolation.
Workflow Decision Tree
1) Implementing a New Repository
- •Use the Surgical Actor Isolation pattern to prevent
deinitconflicts (seereferences/concurrency.md) - •Use
@Observablefor the repository class (seereferences/concurrency.md) - •Implement real-time listeners with proper lifecycle management (see
references/firestore.md)
2) Handling Authentication
- •Bridge Firebase Auth state to SwiftUI using
@Observable(seereferences/auth.md) - •Use
async/awaitfor sign-in and sign-out operations (seereferences/auth.md)
3) Data Operations
- •Use
Codablesupport in Firestore for type-safe data handling (seereferences/firestore.md) - •Use native
async/awaitfor all single-result operations likegetDocuments,addDocument, andsetData(seereferences/concurrency.md) - •For continuous data streams, bridge listeners to
AsyncStream(seereferences/concurrency.md)
Core Guidelines
Concurrency & Isolation
- •Prefer surgical isolation: While class-level
@MainActoris generally recommended for simplicity, we prefer surgical isolation for Firebase repositories to allow non-isolated cleanup indeinit. On Swift 6.2+ (SE-0371), you can alternatively use class-level@MainActorwith anisolated deinit. - •Always clean up: Always remove
AuthStateListenerandListenerRegistrationindeinit. - •Bridge to MainActor: When receiving results from Firebase background closures, use
Task { @MainActor in ... }to update@Observableproperties.
Firestore
- •Use
@DocumentIDfor mapping Firestore document IDs to model properties. - •Use
@ServerTimestampfor managing creation/update dates. - •Order queries explicitly when using real-time listeners to maintain UI stability.
Authentication
- •Check for
currentUserbefore triggering anonymous sign-in to avoid redundant sessions. - •Use
weak selfin Auth state listeners to prevent retain cycles.
References
- •
references/concurrency.md: Surgical actor isolation and async bridging. - •
references/firestore.md: Real-time listeners, CRUD, and Codable patterns. - •
references/auth.md: Authentication state management and async flows.
External References
- •Firebase Documentation
- •Swift Evolution SE-0371
- •Matt Massicotte's Blog (Swift Concurrency Expert)