Decorator 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
- ✓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
Decorator Pattern in Swift: what you actually reach for
Swift implementation
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 FoundationThink 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 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).
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 trialMost AI and dev tools have a student plan. See which ones and how to claim them 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.