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

Decorator 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

  • ✓Decorator Pattern runs in O(1) time and O(n) space, in Swift as in every other language.
  • ✓The object decorator is a struct or class conforming to the same protocol and holding the wrapped value.
  • ✓Write the decorator as a struct conforming to the protocol, and give the protocol a default implementation in an extension so decorators only override what changes.
  • ✓The Swift trap: Property wrappers cannot be applied to computed properties, to protocol requirements, or to variables in a protocol extension, and they cannot be used in an enum, restrictions people discover only after designing around them.
  • ✓A struct decorator conforming to a protocol is statically dispatched and inlined in release builds when the concrete type is known; storing it as an existential (any Store) forces dynamic dispatch and, if the type is larger than the three-word inline buffer, a heap allocation per value.

What Decorator Pattern actually is

The Decorator pattern adds behaviour to an individual object by wrapping it in another object that implements the same interface and forwards to it, so you can stack capabilities (buffering, then compression, then encryption) without a combinatorial explosion of subclasses. Its defining property is that the decorator is INDISTINGUISHABLE from the thing it decorates at the type level, which is what makes stacking work. Reading about it across these eight languages is unusually confusing for one reason: Python, TypeScript and Swift all have a LANGUAGE feature called a decorator or a wrapper that is related but not the same thing, Python decorators transform functions and classes at definition time, TypeScript has two mutually incompatible decorator systems, and Swift property wrappers decorate storage. Meanwhile Go gets the pattern almost for free through embedding, and Rust has no inheritance to avoid in the first place.

Decorator Pattern in Swift: what you actually reach for

The object decorator is a struct or class conforming to the same protocol and holding the wrapped value. Swift additionally has @propertyWrapper, a language feature that decorates STORAGE rather than behaviour: the wrapper type supplies wrappedValue and optionally projectedValue exposed through the dollar prefix. @State, @Published and @AppStorage are all property wrappers. Protocol extensions provide default implementations, which removes much of the forwarding burden.

Swift implementation

Write the decorator as a struct conforming to the protocol, and give the protocol a default implementation in an extension so decorators only override what changes. Use a property wrapper when the concern is genuinely about how a single value is stored or accessed (clamping, persistence, thread confinement) and a wrapper type when the concern is about behaviour. Keep the wrapped value private and expose it through a computed property.
swift
protocol Store {
    func get(_ key: String) -> String?
    func set(_ key: String, _ value: String)
}

// Object decorator: same protocol, holds the wrapped value.
struct Timed<Inner: Store>: Store {
    private let inner: Inner
    init(_ inner: Inner) { self.inner = inner }

    func get(_ key: String) -> String? {
        let t0 = DispatchTime.now().uptimeNanoseconds
        defer { print(key, DispatchTime.now().uptimeNanoseconds - t0) }
        return inner.get(key)
    }

    func set(_ key: String, _ value: String) { inner.set(key, value) }
}

// Property wrapper: decorates STORAGE, a different job entirely.
@propertyWrapper
struct Clamped<Value: Comparable> {
    private var value: Value
    private let range: ClosedRange<Value>

    init(wrappedValue: Value, _ range: ClosedRange<Value>) {
        self.range = range
        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }

    var wrappedValue: Value {
        get { value }
        set { value = min(max(newValue, range.lowerBound), range.upperBound) }
    }
}

struct Settings {
    @Clamped(0...100) var volume: Int = 50
}

// Property wrappers CANNOT decorate computed properties, protocol
// requirements, or enum cases.
import Foundation

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

Property wrappers cannot be applied to computed properties, to protocol requirements, or to variables in a protocol extension, and they cannot be used in an enum, restrictions people discover only after designing around them. A subtler one: a property wrapper on a struct property makes the setter mutating, so a wrapper that stores through a reference behaves differently from one that stores inline, and a wrapper used inside a class does not get value semantics back. And unlike Rust, conforming a wrapper to a protocol still requires writing every requirement, since protocol extensions supply defaults but not forwarding.

Performance in Swift, beyond the O(1)

A struct decorator conforming to a protocol is statically dispatched and inlined in release builds when the concrete type is known; storing it as an existential (any Store) forces dynamic dispatch and, if the type is larger than the three-word inline buffer, a heap allocation per value. Property wrappers compile to a stored property of the wrapper type plus a computed accessor pair, so the cost is an extra function call per access that the optimiser normally removes. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Decorator Pattern between languages.

Real-World Applications

Decorator 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 Decorator Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Decorator 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 Decorator 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 Decorator 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 Decorator Pattern?

The object decorator is a struct or class conforming to the same protocol and holding the wrapped value. Swift additionally has @propertyWrapper, a language feature that decorates STORAGE rather than behaviour: the wrapper type supplies wrappedValue and optionally projectedValue exposed through the dollar prefix. @State, @Published and @AppStorage are all property wrappers. Protocol extensions provide default implementations, which removes much of the forwarding burden.

What is the most common Swift mistake when implementing Decorator Pattern?

Property wrappers cannot be applied to computed properties, to protocol requirements, or to variables in a protocol extension, and they cannot be used in an enum, restrictions people discover only after designing around them. A subtler one: a property wrapper on a struct property makes the setter mutating, so a wrapper that stores through a reference behaves differently from one that stores inline, and a wrapper used inside a class does not get value semantics back. And unlike Rust, conforming a wrapper to a protocol still requires writing every requirement, since protocol extensions supply defaults but not forwarding.

How does Decorator Pattern actually perform in Swift?

A struct decorator conforming to a protocol is statically dispatched and inlined in release builds when the concrete type is known; storing it as an existential (any Store) forces dynamic dispatch and, if the type is larger than the three-word inline buffer, a heap allocation per value. Property wrappers compile to a stored property of the wrapper type plus a computed accessor pair, so the cost is an extra function call per access that the optimiser normally removes. Time complexity is O(1) and space is O(n).

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

Most AI and dev tools have a student plan. See which ones and how to claim them 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.