In Swift, what must a @propertyWrapper type declare, and what does the compiler generate when you write @Trimmed var email: String?
answer
- one required member on the type
- same access level as the wrapper
- private storage with a leading underscore
- a computed property forwards get and set
basics
~20 sA @propertyWrapper type must declare a non-static wrappedValue property. For @Trimmed var email, Swift synthesizes private storage _email of type Trimmed and turns email into a computed property that forwards get and set to _email.wrappedValue.
solid answer
~40 sThe only requirement is a non-static `wrappedValue` property with the same access level as the wrapper type; it can be stored or computed, and the wrapper's initializers may not be failable. When I write `@Trimmed var email: String`, the compiler adds a `private var _email: Trimmed` holding the wrapper instance and makes `email` a computed `String` whose getter reads `_email.wrappedValue` and whose setter writes it. So every read and write runs the wrapper's code, and I can't add my own `get` or `set` to `email`. An `= value` on the declaration becomes a call to `init(wrappedValue:)`, so that initializer must apply the same transformation as the setter, or the first value slips through untouched.
code
swift · 26 lines@propertyWrapper
struct Trimmed {
private var text = ""
var wrappedValue: String {
get { text }
set {
let head = newValue.drop(while: \.isWhitespace)
text = String(head.reversed().drop(while: \.isWhitespace).reversed())
}
}
init(wrappedValue: String) {
self.wrappedValue = wrappedValue // runs the setter, so the first value is trimmed too
}
}
struct SignUpForm {
@Trimmed var email: String
@Trimmed var displayName = ""
}
var form = SignUpForm(email: " [email protected] ")
form.displayName = "\tAda "
print("[\(form.email)] [\(form.displayName)]")
// Prints "[[email protected]] [Ada]"go deeper
Recall the single requirement, a non-static wrappedValue, and that @Name on a var routes its reads and writes through an instance of that type.
Explain the synthesized pair: private _email storage of the wrapper type plus a computed email forwarding to wrappedValue, and which initializer each declaration form calls.
Show you know where wrappers leak: the first value arrives through init(wrappedValue:), not the setter, and a class wrapper makes copies of the containing struct share state.
Judge when a wrapper earns its place over a plain computed property or a dedicated type, given that it hides storage and accessors from readers of the declaring type.
## What a property wrapper is A **property wrapper** is an ordinary Swift `struct`, `enum` or `class` marked with the `@propertyWrapper` attribute. Marking the type creates a **custom attribute** with the same name, so a type called `Trimmed` can be written as `@Trimmed` in front of a variable. The wrapper moves the get and set logic that would otherwise be copied onto every property (trimming input, clamping a number, logging writes) into one reusable type. The property that carries the attribute is called the **wrapped property**; the value it exposes is the **wrapped value**. ## The one requirement: `wrappedValue` The compiler checks a short list of rules on the wrapper type itself: - It must declare an **instance (non-static) property named `wrappedValue`**. Without one, Swift reports `property wrapper type 'Trimmed' does not contain a non-static property named 'wrappedValue'`. - `wrappedValue` must have the **same access level as the wrapper type**. A `public` wrapper with an `internal` `wrappedValue` is rejected. - **No initializer of the wrapper may be failable**: `init?(wrappedValue:)` is an error. - If an initializer has a `wrappedValue` parameter, that parameter's type must equal the `wrappedValue` property's type, or be an `@autoclosure` of it. `wrappedValue` can be stored or computed. Most real wrappers keep private storage and make `wrappedValue` computed, so the setter can transform what is written: ```swift @propertyWrapper struct Uppercased { private var text = "" var wrappedValue: String { get { text } set { text = newValue.uppercased() } } } ``` Everything else (`projectedValue`, extra initializers, methods) is optional. ## What the compiler generates for `@Trimmed var email: String` Writing `@Trimmed var email: String` inside `SignUpForm` makes the compiler synthesize two declarations: 1. A **stored property `_email` of type `Trimmed`**, the wrapper instance itself. Its access level is always `private`. 2. A **computed property `email` of type `String`** whose getter returns `_email.wrappedValue` and whose setter assigns `_email.wrappedValue = newValue`. The wrapper is responsible for storing the value; the compiler only adds storage for the wrapper instance and the forwarding accessors. The hand-written equivalent looks like this: ```swift struct SignUpFormByHand { private var _email: Trimmed var email: String { get { _email.wrappedValue } set { _email.wrappedValue = newValue } } init(email: String) { _email = Trimmed(wrappedValue: email) } } ``` Because `email` is now computed, you cannot add your own `get` or `set` to a wrapped property; the wrapper owns them. ## How the wrapper instance gets created The declaration decides which initializer of the wrapper Swift calls to build `_email`: | Declaration | Wrapper initializer Swift calls | |---|---| | `@Trimmed var email: String` (no value) | `init()` if the wrapper has one; otherwise the struct's initializer must supply the value | | `@Trimmed var displayName = ""` | `init(wrappedValue: "")` | | `@Clamped(0...100) var volume = 50` | `init(wrappedValue: 50, 0...100)` | | `@Clamped(wrappedValue: 50, 0...100) var volume: Int` | `init(wrappedValue:_:)` with those exact arguments | An `=` initial value is sugar for the `wrappedValue:` argument. It goes to the initializer, **not** through the setter, which is why the `Trimmed` example assigns `self.wrappedValue = wrappedValue` inside `init(wrappedValue:)`: that line runs the trimming setter for the first value too. How a wrapper reshapes a struct's memberwise initializer is a separate rule with its own surprises. ## Walking through the sign-up form In the code example, `SignUpForm(email: " [email protected] ")` builds `_email` with `Trimmed(wrappedValue:)`, which trims on the way in. Later, `form.displayName = "\tAda "` calls the synthesized setter, which calls `Trimmed`'s `wrappedValue` setter, which trims again. Every read goes through the getter and returns the clean string. The form type contains no trimming code at all; adding a third trimmed field is one attribute. ## Common mistakes - Expecting a protocol: there is no `PropertyWrapper` protocol to conform to; the attribute plus the `wrappedValue` member is the whole contract. - Reaching for `_email` from outside the type: it is `private`, so only the type's own declaration and its same-file extensions can touch it. - Applying the attribute to a `let` or a computed property: the compiler rejects both, because the wrapper needs mutable storage and owns the accessors. - Storing the initial value directly into private storage in `init(wrappedValue:)` and so skipping the transformation for the first value.
- Why does Trimmed's init(wrappedValue:) assign self.wrappedValue instead of the private text property?An `= value` on a wrapped property, or the memberwise argument, reaches the wrapper through `init(wrappedValue:)`, not through the `wrappedValue` setter. Assigning `self.wrappedValue` after `text` has its default runs the setter, so the first value is trimmed exactly like later writes. Writing `text = wrappedValue` would store the untrimmed string until the next assignment.
- Can a property wrapper be a class, and what changes if it is?Yes: a `struct`, `enum` or `class` can carry `@propertyWrapper`. With a class wrapper the synthesized setter is `nonmutating`, so you can assign the wrapped property through a `let` instance of the containing struct, and copies of that struct share one wrapper object, so a write through one copy shows up in the other.
- What does the compiler say if the wrapper's wrappedValue is declared static?It reports that the property wrapper type does not contain a non-static property named `wrappedValue`. The value belongs to each wrapped property, so it must be an instance property; a `static` member would be shared by every property the wrapper is applied to.
A wrapped property is like a building's mail room: residents still use their own address, but every parcel in or out passes the same desk, which applies one set of rules for the whole building.
- A property wrapper type must conform to a PropertyWrapper protocol.
- The wrapped property stores the String itself and the wrapper only validates it.
- Code outside the type can read _email to reach the wrapper instance.
- init(wrappedValue:) can be failable to reject bad input at declaration time.
- An initial value written with = goes through the wrappedValue setter.