Swift Patterns

高级 Advanced 参考型 Reference ⚡ Claude Code 专属 ⚡ Claude Code Optimized
2 min read · 77 lines

Swift 5.5+ patterns — actor-based thread safety, protocol DI, and persistence layers

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 Sendable types for data crossing actor boundaries
  • Minimal public API — only domain operations
  • Load synchronously in init for simplicity
  • Don't use nonisolated to bypass actor isolation

Part 2: Protocol-Based Dependency Injection

Pattern

  1. Define small, focused protocols — one per external concern
  2. Create production implementations — real file system, network, etc.
  3. Create mock implementations — with configurable error properties
  4. Inject via default parameters — production uses defaults; tests inject mocks
  5. 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 DEBUG instead 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.

相关技能 Related Skills