Strategy 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
- ✓Strategy Pattern runs in O(1) time and O(1) space, in Swift as in every other language.
- ✓Closures are the strategy and the standard library takes them everywhere: sorted(by:), map, filter and reduce.
- ✓Mark stored closures escaping and take non-escaping ones by default, because non-escaping is both the default and the cheaper option.
- ✓The Swift trap: An escaping closure that captures self strongly creates a retain cycle whenever the object also holds the closure, and ARC will never break it: the object leaks silently with no crash and no warning.
- ✓A non-escaping closure can be stack-allocated and frequently inlines completely; an escaping one is heap-allocated as a boxed context.
What Strategy Pattern actually is
Strategy Pattern in Swift: what you actually reach for
Swift implementation
protocol Pricing { func apply(_ cents: Int) -> Int }
struct Percent: Pricing {
let pct: Int
func apply(_ cents: Int) -> Int { cents * (100 - pct) / 100 }
}
final class Cart {
// Stored closure MUST be escaping, and that is what enables the retain cycle.
private let pricing: (Int) -> Int
private var onChange: (() -> Void)?
init(pricing: @escaping (Int) -> Int) { self.pricing = pricing }
func total(_ cents: Int) -> Int { pricing(cents) }
func observe() {
// [weak self] breaks the cycle; without it this class leaks silently.
onChange = { [weak self] in
guard let self else { return }
_ = self.total(1000)
}
}
}
// Generic (specialises, devirtualises) vs existential (witness table, no inline).
func totalFast<P: Pricing>(_ c: Int, _ p: P) -> Int { p.apply(c) }
func totalSlow(_ c: Int, _ p: any Pricing) -> Int { p.apply(c) }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 Strategy Pattern?
Closures are the strategy and the standard library takes them everywhere: sorted(by:), map, filter and reduce. A closure stored beyond the call needs the escaping attribute, which is the compiler making the lifetime question explicit. Protocols with a single requirement are the object form, and protocol extensions let you supply composable defaults. Since Swift 5.7, any Pricing spells an existential and some Pricing an opaque type, and Swift 5.9 added parameter packs for variadic generic strategies.
What is the most common Swift mistake when implementing Strategy Pattern?
An escaping closure that captures self strongly creates a retain cycle whenever the object also holds the closure, and ARC will never break it: the object leaks silently with no crash and no warning. The fix is a capture list, weak self or unowned self, and the choice matters because unowned crashes on access after deallocation while weak yields nil. Non-escaping closures cannot create this cycle, which is exactly why the default is the safe one and why marking something escaping deserves a second look.
How does Strategy Pattern actually perform in Swift?
A non-escaping closure can be stack-allocated and frequently inlines completely; an escaping one is heap-allocated as a boxed context. Calls through any Protocol go through a protocol witness table and cannot inline, whereas a generic function specialised under whole-module optimisation compiles to a direct call. Capturing a large value type by value copies it into the closure context, so capturing a big struct in a strategy created inside a loop is a repeated copy that a capture of a reference would avoid. 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 trialWeighing more options? Compare the best software in each category 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.