Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Strategy Pattern Implementation in Swift

14 min readintermediate
Website QA and SEO audits

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 makes an algorithm a parameter: the caller picks the behaviour, the host object runs it without knowing which one it got. The classic object-oriented formulation wraps each algorithm in a class implementing a common interface, and that formulation exists entirely because the language of the day could not pass a function around. Every language on this page can, so the honest version of this topic is about what a callable IS in each runtime: a plain pointer, a closure over an environment, a boxed object with a vtable, or a delegate that also carries a receiver. The differences that bite are all about the captured environment, because the strategy usually closes over something and the eight languages disagree profoundly about who owns that something and how long it lives.

Strategy Pattern in Swift: what you actually reach for

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.

Swift implementation

Mark stored closures escaping and take non-escaping ones by default, because non-escaping is both the default and the cheaper option. Use trailing closure syntax at the call site, and give multi-closure APIs argument labels so the trailing one is unambiguous. Prefer a generic parameter constrained to a protocol over any Protocol when the type does not need to vary, so the call devirtualises.
swift
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 Free

The Swift-specific 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. 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.

Performance in Swift, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Strategy Pattern between languages.

Real-World Applications

Strategy Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Strategy Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Strategy Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Strategy Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Strategy Pattern to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Weighing more options? Compare the best software in each category on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.