Articles
Doubles pattern in Swift
Learn how to implement the double pattern in pure Swift for testing and instant previews in SwiftUI, without third-party libraries. Protocols, dependency injection, and testable code using only the native capabilities of the language.
The Double Pattern in Swift: Testing and Previews without Third-Party Libraries
Let's talk about one of those patterns that separate developers who copy code from those who understand what they are doing: the double pattern. And no, I'm not talking about movie stunts, I'm talking about how to write testable code, have previews in SwiftUI without waiting 3 minutes for the result to show up, and do it without resorting to third-party libraries or complex dependency injection frameworks. All with pure, hard Swift code.
🎯 The problem no one tells you about
Imagine this: you're developing an app that loads movies from an API. Every time you want to see the view in Xcode's Canvas, you have to wait for the preview to compile, connect to the server, download data... and if you don't have internet or the server is down, the preview fails outright. What's more, when you want to do unit tests on your business logic, you're making real requests to a server, which is slow, unpredictable, and totally inefficient.
Typically, many people turn to third-party libraries to manage this. But as I always say: if there's a native solution, use it. And in this case, there is: protocols + dependency injection. Simple, elegant, pure Swift.
🧠 The concept: loose coupling through protocols
Protocols in Swift are contracts. They define what something should do, but not how it does it. This is loose coupling: your business logic does not depend on a specific implementation, but on a contract.
