Swift Property Wrappers
Sometimes many properties need the same extra behaviour: "always keep this value between 0 and 100", "store this string trimmed", "save this setting to disk". Instead of repeating getter/setter code everywhere, a property wrapper packages that logic once, and you apply it with an @Attribute. SwiftUI's @State, @Binding and @Published are all property wrappers.
Your first property wrapper
A property wrapper is a struct (or class) marked @propertyWrapper that has a wrappedValue property. Whatever wrappedValue does on get/set is what the wrapped property does.
@propertyWrapper
struct Clamped {
private var value: Int
private let range: ClosedRange<Int>
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
}
struct Speaker {
@Clamped(0...100) var volume = 50
}
var speaker = Speaker()
speaker.volume = 140
print(speaker.volume)
speaker.volume = -5
print(speaker.volume)100
0
Code using Speaker just reads and writes volume like a normal Int; the clamping happens behind the scenes.
How it works
When you write @Clamped(0...100) var volume = 50, the compiler generates roughly this:
private var _volume = Clamped(wrappedValue: 50, 0...100)
var volume: Int {
get { _volume.wrappedValue }
set { _volume.wrappedValue = newValue }
}| Part | Purpose |
|---|---|
@propertyWrapper |
marks the type as usable with @Name |
wrappedValue |
required — the value the property exposes |
init(wrappedValue:) |
lets you write = initialValue at the declaration |
projectedValue |
optional extra value, accessed with $name |
A string wrapper
Wrappers can be generic or work with any type. Here is one that trims whitespace and capitalizes names automatically:
import Foundation
@propertyWrapper
struct Trimmed {
private var text = ""
init(wrappedValue: String) {
self.wrappedValue = wrappedValue
}
var wrappedValue: String {
get { text }
set { text = newValue.trimmingCharacters(in: .whitespaces).capitalized }
}
}
struct SignUpForm {
@Trimmed var firstName: String
@Trimmed var city: String
}
var form = SignUpForm(firstName: " ada ", city: "new york ")
print("[\(form.firstName)] from [\(form.city)]")
form.city = " london"
print("[\(form.city)]")[Ada] from [New York]
[London]
Notice that the memberwise initializer of SignUpForm still works — it passes each value through init(wrappedValue:).
Projected values with $
A wrapper can expose a second value through projectedValue. You read it with a $ prefix. SwiftUI uses this for $state bindings; here we use it to count how many times a value changed:
@propertyWrapper
struct Tracked<Value> {
private var value: Value
private(set) var projectedValue = 0 // number of changes
init(wrappedValue: Value) {
value = wrappedValue
}
var wrappedValue: Value {
get { value }
set {
value = newValue
projectedValue += 1
}
}
}
struct Game {
@Tracked var score = 0
@Tracked var level = "Forest"
}
var game = Game()
game.score += 10
game.score += 25
game.level = "Cave"
print("score \(game.score), changed \(game.$score) times")
print("level \(game.level), changed \(game.$level) times")score 35, changed 2 times
level Cave, changed 1 times
Tracked is generic (<Value>), so the same wrapper works for both the Int and the String property.
Wrappers you will meet in SwiftUI
| Wrapper | What it does |
|---|---|
@State |
stores simple view-local state; changing it redraws the view |
@Binding |
a reference to state owned by another view ($value) |
@Observable / @Bindable |
observable model objects (a macro plus a wrapper) |
@Environment |
reads values like color scheme or dismiss actions |
@AppStorage |
reads/writes a value in UserDefaults |
Note: A wrapper applies to stored properties (and local variables). It cannot be used on computed properties, and a wrapped property cannot also be
lazyorweak.
Tip: Don't overuse wrappers. If the logic is used by only one property, a
didSetobserver is usually clearer.
Test yourself
Which member must every property wrapper type have?
- projectedValue
- wrappedValue
- init()
- didSet
Given @Tracked var score = 0, what does $score access?
- The wrapper's projectedValue
- The original initial value
- A copy of score
- A compile error
Which of these is a property wrapper used in SwiftUI?
- @main
- @State
- @escaping
- @discardableResult