Factory Pattern Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Factory Pattern runs in O(1) time and O(1) space, in Swift as in every other language.
- ✓Swift splits the job between static factory methods, protocol existentials and enums. A static func make on the type is the plain form; returning some Protocol gives an opaque type with static dispatch and no box, while any Protocol gives an existential that can hold different concrete types at runtime.
- ✓Return some Protocol when the function always produces one concrete type and you only want to hide it, and any Protocol when it genuinely varies.
- ✓The Swift trap: A protocol with an associated type or a Self requirement cannot be used as an existential before Swift 5.7, and even after it the compiler rejects using it where the associated type would have to be known, which is why a seemingly simple factory returning any Collection fails to compile.
- ✓Existentials use an inline value buffer of three words; a product larger than that is heap-allocated and boxed, so returning any Parser can allocate where returning some Parser never does.
What Factory Pattern actually is
Factory Pattern in Swift: what you actually reach for
Swift implementation
protocol Parser {
func parse(_ raw: String) -> Int
}
struct JSONParser: Parser { func parse(_ raw: String) -> Int { raw.count } }
struct CSVParser: Parser { func parse(_ raw: String) -> Int { raw.split(separator: ",").count } }
extension Parser where Self == JSONParser {
// Reads as Parser.json at the call site.
static var json: JSONParser { JSONParser() }
}
enum Kind { case json, csv }
// 'any' is an EXISTENTIAL: boxed if larger than the 3-word inline buffer.
func makeParser(_ kind: Kind) -> any Parser {
switch kind {
case .json: return JSONParser()
case .csv: return CSVParser()
}
}
// 'some' is OPAQUE: one concrete type, static dispatch, no box.
func makeJSON() -> some Parser { JSONParser() }Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Factory Pattern?
Swift splits the job between static factory methods, protocol existentials and enums. A static func make on the type is the plain form; returning some Protocol gives an opaque type with static dispatch and no box, while any Protocol gives an existential that can hold different concrete types at runtime. Since Swift 5.7 the any keyword is required to spell an existential, and protocols with associated types or Self requirements finally became usable as existentials in that release, which had blocked the pattern for years. Enums with associated values are frequently the better answer for a closed family.
What is the most common Swift mistake when implementing Factory Pattern?
A protocol with an associated type or a Self requirement cannot be used as an existential before Swift 5.7, and even after it the compiler rejects using it where the associated type would have to be known, which is why a seemingly simple factory returning any Collection fails to compile. The other trap is silent: a static factory on a non-final class returning Self behaves differently from one returning the concrete class name when subclassed, and marking the class final removes a whole family of surprises along with the dynamic dispatch cost.
How does Factory Pattern actually perform in Swift?
Existentials use an inline value buffer of three words; a product larger than that is heap-allocated and boxed, so returning any Parser can allocate where returning some Parser never does. Opaque return types are monomorphised and dispatch statically, so they inline. Whole-module optimisation can devirtualise calls on a final class or an internal type with a single implementation, which is the main reason marking classes final measurably helps in Swift and is a routine review comment. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.