Swift Patterns
Files: skills/swift-actor-persistence/SKILL.md + skills/swift-protocol-di-testing/SKILL.md
-------|-----------|
| Actor (not class + lock) | Compiler-enforced thread safety |
| In-memory cache + file persistence | Fast reads, durable writes |
| Dictionary keyed by ID | O(1) lookups |
| Generic over Codable & Identifiable | Reusable across model types |
| Atomic file writes | Prevents corruption on crash |
Best Practices
- Use
Sendabletypes for data crossing actor boundaries - Minimal public API — only domain operations
- Load synchronously in
initfor simplicity - Don't use
nonisolatedto bypass actor isolation
Part 2: Protocol-Based Dependency Injection
Pattern
- Define small, focused protocols — one per external concern
- Create production implementations — real file system, network, etc.
- Create mock implementations — with configurable error properties
- Inject via default parameters — production uses defaults; tests inject mocks
- Write tests with Swift Testing —
@Test,#expect(throws:)
Key Principles
- Single Responsibility: One protocol per concern
- Sendable conformance: Required for actor boundaries
- Only mock boundaries: Mock external dependencies, not internal types
- Error simulation: Design mocks with configurable error properties
Anti-Patterns
- God protocols covering all external access
- Mocking internal types with no external dependencies
#if DEBUGinstead of proper DI- Over-engineering: no protocol needed if no external dependencies
Remember: Swift's actor model and protocol system provide compile-time safety guarantees for concurrency and testability.