Swift property wrappers
When writing business code you often meet the same kinds of needs: add range validation to a property, automatically convert formats on read/write, and sync values to UserDefaults.
Hand-writing this logic for every property is both verbose and error-prone.
Property wrappers (property wrapper, SE-0258, introduced in Swift 5.1) are designed for exactly this: extract the layer of logic attached to reading and writing a property into a reusable type, then apply it to a property with @ syntax.
What is a property wrapper?
A property wrapper is essentially a type marked with @propertyWrapper that must provide a property named wrappedValue.
The user adds @WrapperName when declaring a property; reading or writing that property then goes through the wrapper's wrappedValue getter and setter.
In other words, the wrapper packages "storage + extra logic" into a type, leaving only a single annotation at the property declaration.
| Role | Where to write it | Responsibility |
|---|---|---|
| Wrapper type | A struct / class / enum marked with @propertyWrapper | Implements wrappedValue, handling the actual read/write logic |
| Wrapped property | The user's @Wrapper var x: T |
Declares the wrapped property, expressing only the business intent |
| wrappedValue | Inside the wrapper type | The outward-facing value, returned by the getter and received by the setter |
| projectedValue | Inside the wrapper type (optional) | An extra projected value, accessed through $x Access the |
@propertyWrapper syntax
Let's start with a minimal working wrapper that clamps a value to a given range on write.
Example
import Foundation
// Marked with @propertyWrapper; the @ before the type name is only used when declaring a property
@propertyWrapper
struct
Clamped
{
private
var value
:
Int
// Where the value is actually stored
let range
:
ClosedRange
<
Int
// The allowed range
// The wrappedValue parameter corresponds to the initial value at the property declaration
init
(
wrappedValue
:
Int, _ range
:
ClosedRange
<
Int
)
{self.
range
=
range
// Clamp during initialization too, otherwise the initial value may be out of 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
Player
{
@Clamped
(
0
...
100
)
var health
:
Int
=
120
// The initial value 120 is clamped to 100
@Clamped
(
1
...
10
)
var level
:
Int
=
3
}
var player
=
Player
(
)
(
player.
health
)
player.
health
=
250
(
player.
health
)
player.
health
=
5
(
player.
health
)
(
player.
level
)
Running result:
100
100
0
3
The = 120 in the property declaration is passed to the wrappedValue parameter of init(wrappedValue:), and the 0...100 in parentheses corresponds to the remaining parameters in init.
What does the compiler do?
An annotated property is rewritten by the compiler into "a wrapper stored property + a computed property".
The two code snippets below are just illustrations, reusing the Clamped type defined above, to help you understand the correspondence between them.
Example
// The code you write (see the Clamped definition above)
struct
Player
{
@Clamped
(
0
...
100
)
var health
:
Int
=
120
}
It is equivalent to the following hand-written form, except that the underscored property's name is generated by the compiler:
Example
// The equivalent structure generated by the compiler (illustrative, see the Clamped definition above)
struct
Player
{
private
var _health
=
Clamped
(
wrappedValue
:
120
,
0
...
100
)
var health
:
Int
{
get
{
_health.
wrappedValue
}
set
{
_health.
wrappedValue
=
newValue
}
}
}
The underscore-prefixed _health is the wrapper instance itself; it is private outside the type but can be accessed directly inside the type that declares it.
Example
import Foundation
@propertyWrapper
struct
Clamped
{
private
var value
:
Int
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
Player
{
@Clamped
(
0
...
100
)
var health
:
Int
=
120
// Inside the type you can access _health directly to get the wrapper instance
func describe
(
)
{
(
"Range: (_health.range), current value: (health)"
)
}
}
var player
=
Player
(
)
player.
describe
(
)
player.
health
=
999
player.
describe
(
)
Running result:
取值范围:0...100,当前值:100
取值范围:0...100,当前值:100
If you only write @Clamped(0...100) var health: Int without giving an initial value, the compiler has nothing to pass to wrappedValue, so the wrapper must additionally provide an initializer that does not take a wrappedValue parameter, otherwise a compile-time error occurs.
wrappedValue and projectedValue
wrappedValue is the core of the wrapper; all outward reads and writes go through it.
projectedValue is an optional second outlet that gives the property an "extra perspective", accessed through the $ prefix.
| members | Access Method | Required | Typical use |
|---|---|---|---|
| wrappedValue | Writing the property name directly, such as player.health |
Must | The actual value after validation, conversion, and persistence |
| projectedValue | Addition $, such as player.$health |
Optional | Exposes wrapper state, returns a binding or publisher |
The following wrapper capitalizes the first letter on write and uses the projected value to return an all-uppercase version.
Example
import Foundation
@propertyWrapper
struct
Capitalized
{
private
var value
:
String
=
""
// A property with an initial value calls this initializer
init
(
wrappedValue
:
String
)
{
self.
wrappedValue
=
wrappedValue
}
var wrappedValue
:
String
{
get
{
value
}
set
{
value
=
Capitalized.
transform
(
newValue
)
}
}
// projectedValue is accessed through $
var projectedValue
:
String
{
return
wrappedValue.
uppercased
(
)
}
private
static
func transform
(
_ text
:
String
)
String
{
guard let first
=
text.
first
else
{
return
text
}
return
String
(
first
)
.
uppercased
(
)
text.
dropFirst
(
)
}
}
struct
Site
{
@Capitalized var name
:
String
=
"runoob"
}
var site
=
Site
(
)
(
site.
name
)
site.
name
=
"www.runoob.com"
(
site.
name
)
(
site.$name
)
Running result:
Runoob
Www.runoob.com
WWW.RUNOOB.COM
You can see that site.name only capitalizes the first letter, while site.$name goes through the projected value and returns all uppercase.
projectedValue 's type is up to you; it does not have to be the same as wrappedValue . In SwiftUI, the @State uses the projected value to return a Binding。
Practical Examples
The value of property wrappers lies in reuse. The following three examples cover the three common needs of validation, conversion, and persistence.
@Clamped limits the value range
This wrapper appeared earlier; it clamps out-of-range values back into the interval, suiting properties with upper and lower bounds such as health, progress, and volume.
Example
import Foundation
@propertyWrapper
struct
Clamped
{
private
var value
:
Int
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
Progress
{
@Clamped
(
0
...
100
)
var percent
:
Int
=
0
}
var task
=
Progress
(
)
task.
percent
=
30
(
task.
percent
)
task.
percent
=
150
(
task.
percent
)
Running result:
30
100
@UserDefault automatically reads and writes UserDefaults
Encapsulate the logic of "reading with a default value and writing in sync with UserDefaults" into the wrapper, so business properties no longer need a bunch of object(forKey:) and set(_:forKey:).
Example
import Foundation
@propertyWrapper
struct
UserDefault
<
T
{let key
:
String
// The key used in UserDefaults
let defaultValue
:
T
// The default value returned when the key does not exist
var wrappedValue
:
T
{
get
{
UserDefaults.
standard
.
object
(
forKey
:
key
)
as
?
T
??
defaultValue
}
set
{
UserDefaults.
standard
.
set
(
newValue, forKey
:
key
)
}
}
}
struct
Settings
{
@UserDefault
(
key
:
"runoob_nickname"
, defaultValue
:
"Guest"
)
var nickname
:
String
@UserDefault
(
key
:
"runoob_score"
, defaultValue
:
0
)
var score
:
Int
}
// Clear the old value first to ensure this demo starts from the default value
UserDefaults.
standard
.
removeObject
(
forKey
:
"runoob_nickname"
)
var settings
=
Settings
(
)
(
settings.
nickname
)
settings.
nickname
=
"RUNOOB user"
(
settings.
nickname
)
settings.
score
=
99
(
settings.
score
)
Running result:
游客
RUNOOB 用户
99
Since the generic T cannot be guaranteed to be directly storable in UserDefaults, this simplified version only suits basic types such as String, Int, Bool, and Double.
@Capitalized automatically capitalizes the first letter
Conversion wrappers suit handling display formats uniformly, such as names, titles, and labels.
Example
import Foundation
@propertyWrapper
struct
Capitalized
{
private
var value
:
String
=
""
init
(
wrappedValue
:
String
)
{
self.
wrappedValue
=
wrappedValue
}
var wrappedValue
:
String
{
get
{
value
}
set
{
guard let first
=
newValue.
first
else
{
value
=
newValue
return
}
value
=
String
(
first
)
.
uppercased
(
)
newValue.
dropFirst
(
)
}
}
}
struct
Article
{
@Capitalized var title
:
String
=
"swift property wrapper"
}
var article
=
Article
(
)
(
article.
title
)
article.
title
=
"runoob tutorial"
(
article.
title
)
Running result:
Swift 属性包装器
Runoob 教程
Differences from lazy and computed properties
Property wrappers, computed properties, and lazy can all insert logic when reading or writing a property, but their roles are completely different.
A computed property "recomputes on every access", lazy "initializes once on first access", and a property wrapper "turns this logic into a reusable type".
Example
import Foundation
struct
Counter
{
var raw
:
Int
=
0
// Computed property: runs on every read
var
double
:
Int
{
(
"Computed property accessed"
)
return
raw
2
}
// lazy stored property: initialized only once on first access
lazy var heavy
:
String
=
{
(
"lazy initialization runs only once"
)
return
"RUNOOB data"
}
(
)
}
var counter
=
Counter
(
)
(
counter.
double
)
(
counter.
double
)
(
counter.
heavy
)
(
counter.
heavy
)
Running result:
计算属性被访问
0
计算属性被访问
0
lazy 初始化只执行一次
RUNOOB 数据
RUNOOB 数据
| Comparison Item | Computed Properties | lazy stored property | Property wrapper |
|---|---|---|---|
| Does it store a value? | No storage, computed every time | Stored, initialized only once | Storage determined inside the wrapper |
| Execution Timing | Runs on every read and write | Runs once on first access | Every read and write goes through wrappedValue |
| Can it be reused? | No, each property is written separately | No | Yes, one piece of logic applies to any number of properties |
| Can it take parameters? | No | No | Yes, via an initializer that takes a range, key name, etc. |
| Typical use | A value derived from other properties | Delayed creation of an expensive object | Unified validation, conversion, persistence, and thread safety |
Choose based on the need: use a computed property for a derived value; use lazy if you only want to delay creation once; only write a property wrapper when the same logic must be reused across multiple properties.
Property wrappers are not free. They add a layer of type and a method call; in extremely performance-sensitive cases you can measure first and decide. In most business code, the gains in readability and reuse far outweigh the cost.
Common questions
Below are the most common questions about using property wrappers.
Can a wrapper be a class or enum?
Yes. All three kinds of type can be marked @propertyWrapper, as long as they provide wrappedValue.
In practice, however, most wrappers use structs, because their semantics are simple and they have no reference-sharing issues.
Can wrappedValue be read-only?
Yes. A wrappedValue that provides only a getter makes the wrapped property read-only, and writing to it is a compile-time error.
Can multiple wrappers be stacked on one property?
Yes, they take effect from outside to inside.
But stacking multiple layers makes the read/write path hard to trace; unless truly necessary, keep it to no more than two layers.
Why does my wrapper report a missing init(wrappedValue:)?
Because the property declaration provides an initial value, but the wrapper has no initializer that can receive it.
The fix is to add init(wrappedValue:), or remove the initial value on the property and assign it elsewhere.
Can a property wrapper be used on let?
No. A wrapped property must be var, because it needs a setter to be written.
Can projectedValue be omitted?
Yes. When projectedValue is not implemented, $PropertyName is a compile-time error, but ordinary reads and writes are unaffected.