Property wrappers
suggest changeSome property logic shows up over and over: trim whitespace from a string, keep a number inside a range, remember earlier values, guard a value with a lock. You can write it with a private stored property and a computed property in front of it, or with property observers, but then you copy the same few lines into every type that needs it.
A property wrapper, added in Swift 5.1, puts that logic into a type of its own. You then apply it to a property with an attribute:
struct User {
@Trimmed var name: String
@Clamped(0...120) var age = 0
}
This article covers:
- writing a wrapper with
@propertyWrapperandwrappedValue - what the compiler generates for a wrapped property
- passing arguments to a wrapper, like the range in
@Clamped(0...120) projectedValueand the$namesyntax- wrappers on function parameters, closure parameters and local variables
- combining a wrapper with
didSet, and stacking several wrappers - a thread-safe
@Lockedwrapper, and why it isn't as safe as it looks - the rules and limits
The examples were compiled and run with Swift 6.4 on Windows, in the Swift 6 language mode:
swiftc -swift-version 6 main.swift -o main.exe
A first wrapper: @Trimmed
A property wrapper is a struct, class or enum marked with @propertyWrapper. It must have a property named wrappedValue. That is the value the user of the wrapped property sees:
import Foundation
@propertyWrapper
struct Trimmed {
private var value: String = ""
var wrappedValue: String {
get { value }
set { value = newValue.trimmingCharacters(in: .whitespacesAndNewlines) }
}
init(wrappedValue: String) {
self.wrappedValue = wrappedValue
}
}
struct User {
@Trimmed var name: String
@Trimmed var email: String = ""
}
var user = User(name: " Alice \n")
print("[\(user.name)]")
user.email = " alice@example.com "
print("[\(user.email)]")
user.name += " "
print("[\(user.name)]")
Output:
[Alice]
[alice@example.com]
[Alice]
How it works:
- Reading
user.namecalls the getter ofwrappedValue, and assigning to it calls the setter, which trims the string. init(wrappedValue:)is what lets you write an initial value,@Trimmed var email: String = "". The compiler turns it intoTrimmed(wrappedValue: "").- The initializer assigns through
self.wrappedValue, notvalue, so the initial value is trimmed too.User(name: " Alice \n")stores"Alice". - Compound assignments like
+=read the value, change it and write it back, so they go through the setter as well. - The memberwise initializer of
Userstill takes a plainStringforname. The wrapper is invisible from the outside.
What the compiler generates
A wrapped property is shorthand. For @Trimmed var name: String the compiler creates a private stored property _name of the wrapper type, and turns name into a computed property that forwards to it. This hand-written struct is equivalent:
// What the compiler generates for `@Trimmed var name: String`
struct UserByHand {
private var _name: Trimmed
var name: String {
get { _name.wrappedValue }
set { _name.wrappedValue = newValue }
}
init(name: String) {
_name = Trimmed(wrappedValue: name)
}
}
struct User {
@Trimmed var name: String
func debug() {
// the backing storage is visible inside the type
print(type(of: _name), "->", _name.wrappedValue)
}
}
let a = UserByHand(name: " Bob ")
print("[\(a.name)]")
User(name: " Carol ").debug()
Output:
[Bob]
Trimmed -> Carol
The _name backing property is always private. Code inside the type can use it, which is useful in initializers, as you'll see in the next section. Code outside the type can't.
Because name becomes a computed property that sits in front of _name, a wrapper is a reusable version of the "private storage plus computed property" pattern from Computed properties.
Wrapper arguments: @Clamped
A wrapper can take extra configuration. Add more parameters to init(wrappedValue:...), and pass them in parentheses after the attribute:
@propertyWrapper
struct Clamped<Value: Comparable> {
private var value: Value
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 Mixer {
@Clamped(0...100) var volume = 50
@Clamped(-1.0...1.0) var balance = 0.0
}
var m = Mixer()
print(m.volume, m.balance)
m.volume = 150
m.balance = -3
print(m.volume, m.balance)
m.volume -= 120
print(m.volume)
let custom = Mixer(volume: 500, balance: 0.25)
print(custom.volume, custom.balance)
Output:
50 0.0
100 -1.0
0
100 0.25
@Clamped(0...100) var volume = 50 becomes Clamped(wrappedValue: 50, 0...100). The initial value always goes to the wrappedValue: parameter, and the attribute arguments fill the remaining parameters. Clamped is generic, and Swift infers Value from the initial value: Int for volume, Double for balance.
The memberwise initializer Mixer(volume:balance:) still takes plain values. The value 500 passes through init(wrappedValue:_:), so it is clamped to 100.
Wrapper arguments without an initial value
If you write attribute arguments, Swift builds the wrapper right where the property is declared. Without an initial value there is nothing to pass as wrappedValue, so this doesn't compile:
struct Player {
@Clamped(1...10) var level: Int
// error: missing argument for parameter 'wrappedValue' in call
}
To take the value in an initializer, leave the arguments off the attribute and create the wrapper yourself by assigning to the backing property _level:
struct Player {
var name: String
@Clamped var level: Int
init(name: String, level: Int) {
self.name = name
_level = Clamped(wrappedValue: level, 1...10)
}
}
let p = Player(name: "Ann", level: 42)
print(p.name, p.level)
Output:
Ann 10
projectedValue and $name
A wrapper can expose a second value, the projected value. Define a property named projectedValue, and Swift gives the wrapped property a companion with a $ in front of its name. The projected value can be of any type. Here it is the full list of values the property has had:
@propertyWrapper
struct History<Value> {
private var values: [Value]
init(wrappedValue: Value) {
values = [wrappedValue]
}
var wrappedValue: Value {
get { values.last! }
set { values.append(newValue) }
}
var projectedValue: [Value] { values }
}
struct Document {
@History var title = "Untitled"
}
var doc = Document()
doc.title = "Draft"
doc.title = "Final"
print(doc.title)
print(doc.$title)
print(type(of: doc.$title))
Output:
Final
["Untitled", "Draft", "Final"]
Array<String>
Unlike _title, which is private, $title has the same access level as title, so code outside the type can use it.
Projecting the wrapper itself
A common pattern is to make the projected value the wrapper itself. Then $name gives callers access to the wrapper's own methods. This is how SwiftUI's @State hands out a Binding through $name. Give projectedValue a setter as well, and callers can also call mutating methods through it:
@propertyWrapper
struct Undoable<Value> {
private var past: [Value] = []
private var current: Value
init(wrappedValue: Value) {
current = wrappedValue
}
var wrappedValue: Value {
get { current }
set {
past.append(current)
current = newValue
}
}
// $name gives access to the wrapper itself
var projectedValue: Undoable<Value> {
get { self }
set { self = newValue }
}
var canUndo: Bool { !past.isEmpty }
mutating func undo() {
if let previous = past.popLast() {
current = previous
}
}
}
struct Editor {
@Undoable var text = ""
}
var editor = Editor()
editor.text = "Hello"
editor.text += ", world"
print(editor.text)
editor.$text.undo()
print(editor.text)
editor.$text.undo()
print("[\(editor.text)] canUndo: \(editor.$text.canUndo)")
Output:
Hello, world
Hello
[] canUndo: false
editor.$text.undo() reads the wrapper through the getter, calls undo() on that copy, and writes the copy back through the setter. Without the setter, $text would be read-only and calling a mutating method on it would not compile.
Wrappers on parameters and local variables
Since Swift 5.4 you can use a wrapper on a local variable, and since Swift 5.5 on a function or closure parameter:
// Trimmed and Clamped as defined above
// a wrapper on a function parameter
func greet(@Trimmed _ name: String) {
print("Hello, \(name)!")
}
func setBrightness(@Clamped(0...100) to level: Int) {
print("brightness:", level)
}
greet(" Dana ")
setBrightness(to: 140)
setBrightness(to: -5)
// a wrapper on a closure parameter
let shout = { (@Trimmed text: String) in
print(text.uppercased() + "!")
}
shout(" hey ")
// a wrapper on a local variable
func readCommand() {
@Trimmed var command = " quit \n"
print("[\(command)]")
command = " help "
print("[\(command)]")
}
readCommand()
Output:
Hello, Dana!
brightness: 100
brightness: 0
HEY!
[quit]
[help]
A parameter wrapper doesn't change the function's type. greet still takes a String, and the caller passes a plain value. Inside the function, the argument goes through init(wrappedValue:) before the body runs. Like any parameter, name is a constant inside the function, so you can't assign to it.
Passing the projected value
If the wrapper also has an init(projectedValue:), the caller can pass the projected value instead of the wrapped value. The argument label then gets a $ in front:
@propertyWrapper
struct History<Value> {
private var values: [Value]
init(wrappedValue: Value) { values = [wrappedValue] }
init(projectedValue: [Value]) { values = projectedValue }
var wrappedValue: Value {
get { values.last! }
set { values.append(newValue) }
}
var projectedValue: [Value] { values }
}
func describe(@History title: String) {
print("current: \(title), earlier: \($title.dropLast())")
}
struct Document {
@History var title = "Untitled"
}
var doc = Document()
doc.title = "Draft"
doc.title = "Final"
describe(title: "Notes") // uses init(wrappedValue:)
describe($title: doc.$title) // uses init(projectedValue:)
Output:
current: Notes, earlier: []
current: Final, earlier: ["Untitled", "Draft"]
SwiftUI uses this for bindings: a parameter declared as @Binding var isOn: Bool can be called with $isOn: $settings.isOn.
Observers and stacked wrappers
A wrapped property can still have willSet and didSet. They run around the wrapper's setter, so didSet sees the value after the wrapper has changed it:
struct Thermostat {
@Clamped(10...30) var target = 20 {
didSet { print("target \(oldValue) -> \(target)") }
}
}
var t = Thermostat()
t.target = 25
t.target = 99
Output:
target 20 -> 25
target 25 -> 30
You can also apply several wrappers to one property. They nest from the outside in: the first attribute is the outermost wrapper.
struct Speaker {
@History @Clamped(0...10) var volume = 5
}
var s = Speaker()
s.volume = 8
s.volume = 50
print(s.volume)
print(s.$volume.map(\.wrappedValue))
print(type(of: s.$volume))
Output:
10
[5, 8, 10]
Array<Clamped<Int>>
The backing property has the type History<Clamped<Int>>, and volume reads _volume.wrappedValue.wrappedValue. The value is clamped first, then recorded. The output also shows the weak spots of stacking:
- The outer wrapper must be generic, because its
wrappedValueis the inner wrapper, not anInt.@Trimmedcould not be the outer wrapper here, since itswrappedValueis always aString. - Only the outermost wrapper's projected value is reachable.
$volumeis an array ofClamped<Int>values, not ofInts.
Keep stacks short. If you need two behaviors together often, a single wrapper that does both is usually clearer.
A thread-safe wrapper and its limits
A popular use of property wrappers is an "atomic" property: a wrapper that takes a lock in its getter and setter. Here is one built on Mutex from the Synchronization module (see Mutex and Atomic with the Synchronization module):
import Dispatch
import Synchronization
@propertyWrapper
final class Locked<Value: Sendable>: Sendable {
private let mutex: Mutex<Value>
init(wrappedValue: Value) {
mutex = Mutex(wrappedValue)
}
var wrappedValue: Value {
get { mutex.withLock { $0 } }
set { mutex.withLock { $0 = newValue } }
}
var projectedValue: Locked<Value> { self }
func withLock<R: Sendable>(_ body: (inout Value) -> R) -> R {
mutex.withLock { body(&$0) }
}
}
final class Stats: @unchecked Sendable {
@Locked var hits = 0
@Locked var misses = 0
}
let stats = Stats()
DispatchQueue.concurrentPerform(iterations: 100_000) { _ in
stats.hits += 1 // get, then set: two separate locks
stats.$misses.withLock { $0 += 1 } // one lock around the whole update
}
print("hits: ", stats.hits)
print("misses:", stats.misses)
Output (the hits number is different on every run):
hits: 15260
misses: 100000
Both counters are updated 100,000 times, but hits lost most of its increments. Every single read and every single write is protected, yet stats.hits += 1 is a read followed by a write. Two threads can both read 41 and both write 42. The lock is released between the two steps, and that gap is exactly where the race happens. The same is true for array.append(x) or dict[key] = value on a locked collection: they read the whole value, change the copy and write it back.
misses is correct because withLock holds the lock for the whole read-modify-write. A wrapper can only offer that through an extra method like this one, which you reach through $misses. At that point the wrapper is mostly a lock with extra syntax.
There are more problems:
- Swift 6 doesn't trust it. The backing property
_hitsis avar, so a class that declaresfinal class Stats: Sendablegets "stored property '_hits' of 'Sendable'-conforming class 'Stats' is mutable". You need@unchecked Sendable, which turns off the compiler's checks for the whole class. - Reference semantics.
Lockedmust be a class, because aMutexcan't be copied. If you use it inside a struct, copies of the struct share the same lock and the same value, which is surprising for a value type. - No consistency between properties. Each property has its own lock, so nothing keeps
hitsandmissesconsistent with each other.
For real code, prefer to make the lock visible: store a Mutex and call withLock around each whole operation, use Atomic for a single counter, or use an actor. A locking property wrapper is fine for a value that is only ever read or replaced as a whole, such as a configuration object that is swapped in one assignment.
Rules and limits
The compiler rejects a wrapper in these places (the messages are from Swift 6.4):
- On a
let. "property wrapper can only be applied to a 'var'". Function parameters are the exception, and they're constants anyway. - On a computed property. The wrapper provides the storage, so the property must be stored.
- With
lazy,weak,unownedor@NSCopying. "property 'b' with a wrapper cannot also be lazy". If you need lazy initialization, see Lazy stored properties, or write a wrapper that does it. - In a protocol. A protocol can require
var x: Int { get set }, but it can't require that the property is wrapped. - On an instance property in an extension. Extensions can't add stored properties, and the backing property is stored. Static properties in extensions are fine.
- In top-level code of
main.swiftor a script: "property wrappers are not yet supported in top-level code". Local variables inside functions are fine. - With a throwing or
asyncgetter. "property wrapper's 'wrappedValue' property cannot define an 'async' or 'throws' getter". A wrapper can't report a failure through the property. Clamp, fix up, or store the error and expose it throughprojectedValue.
Static properties can be wrapped, but in the Swift 6 language mode a static var is global mutable state, so it must be isolated to an actor such as @MainActor, or the compiler reports it as not concurrency-safe.
Wrappers you'll meet in practice
Property wrappers are most visible in frameworks:
- SwiftUI (Apple platforms only):
@State,@Binding,@Environment,@AppStorage,@FocusState.@Stateprojects aBindingthrough$name. - Combine (Apple platforms only):
@Publishedprojects a publisher through$name. - Swift Argument Parser (all platforms):
@Argument,@Optionand@Flagdeclare command-line arguments as properties.
Some of these jobs have moved to macros. The @Observable macro from the Observation module replaced ObservableObject with @Published for SwiftUI models. A macro generates new code at compile time, while a property wrapper is an ordinary type that wraps one value at run time. The Macros article covers how they differ in detail.
Summary
- Mark a type with
@propertyWrapperand give it awrappedValueproperty. Apply it with@Name var x. init(wrappedValue:)lets users write an initial value. Extra init parameters become attribute arguments:@Clamped(0...100) var volume = 50.- The compiler creates a private backing property
_xof the wrapper type and turnsxinto a computed property. Assign_xyourself in an initializer when the wrapper needs arguments but the value comes later. projectedValueadds$x, which has the same access level asx. Returningselfgives callers access to the wrapper's methods.- Wrappers also work on local variables (Swift 5.4) and on function and closure parameters (Swift 5.5).
init(projectedValue:)lets callers pass$label: value. didSetsees the value after the wrapper's setter has run. Stacked wrappers nest from the outside in, and only the outermost projection is reachable.- A lock inside
wrappedValueprotects each read and write, not+=orappend. For shared state useMutex,Atomicor an actor directly. - Wrappers can't be used on
let, computed,lazyor protocol properties, in extensions or in top-level code, andwrappedValuecan't throw.