Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 146 ยท Functions and Closures

Property Wrappers

Learn Swift property wrappers - wrappedValue, projected values with $, wrapper initializers and arguments, a Clamped and Trimmed example, local use, limits and when a wrapper is the right tool.

Imagine you have ten properties in your program that should never be negative, three that must always be trimmed of spaces, and two that should print a message whenever they change. You could write a didSet observer on every one of them, repeating the same lines. Or you could write the rule once, give it a name, and attach it to each property with one word. That is what a property wrapper does.

A property wrapper is a type that controls how a property is stored and read. You may already have seen them in SwiftUI (@State, @Binding) or in the @Published and @AppStorage attributes. Those are ordinary Swift types, not compiler magic, and in this lesson you will build your own: from the smallest possible wrapper to a configurable @Clamped, a wrapper that exposes extra information through $, and the rules and limits you should know before using them in a real codebase.

The idea: a type that stores and guards a value

Here is the manual version of the problem. A volume setting must stay between 0 and 100. Without a wrapper you write a stored property and a guard around it:

Swift Doing it by hand with didSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It works, but if Settings also has brightness and contrast, you copy the same six lines three times. The wrapper version moves the rule into a type.

Your first property wrapper

A property wrapper is a struct (or class, or enum) marked with @propertyWrapper that has a property named wrappedValue. Reading and writing the wrapped property calls wrappedValue's getter and setter.

Swift A simple wrapper that clamps to 0...100

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Look at how little the call site says: @Percentage var volume = 50. Everything else, the clamping, lives in Percentage. Several things happen behind the scenes:

  1. The compiler creates a hidden stored property of type Percentage (named _volume) inside Settings.
  2. The initial value 50 is passed to Percentage.init(wrappedValue:).
  3. Every read of settings.volume calls wrappedValue's getter on the hidden property, and every write calls the setter.
  4. The memberwise initializer Settings(volume:brightness:) still takes plain Int values, which are run through the same wrapper (so 500 becomes 100).

You can look at the hidden property from inside the type, which helps to understand what is happening:

Swift The hidden storage property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Inside Counter, count is the wrapped value (an Int) and _count is the wrapper instance (a Tracked). From the outside, only count is visible, because the hidden property is private.

Making the wrapper configurable

A wrapper can take arguments, so one type serves many ranges. You pass them in parentheses after the attribute name, and they go to a custom initializer. Here is the classic generic Clamped wrapper, working with any Comparable type:

Swift Clamped with a range argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The syntax @Clamped(0...100) var health = 100 calls Clamped(wrappedValue: 100, 0...100): the value after = goes to the wrappedValue: parameter and the attribute's arguments fill the other parameters. Because Clamped is generic, the compiler infers Value as Int for health and as Double for progress.

Notice that clamping happens on the initial value too (see weak: 500 becomes 100, 0 becomes 1). A wrapper that only validated later assignments would leave an invalid starting state, a common bug.

If a wrapper has no init(wrappedValue:), you cannot give the property a default value with =. Instead you write @Clamped(0...100) var health and the wrapper's own init(range:) creates it. Both forms are valid; pick whichever matches how the wrapper should be used.

Projected values and the $ prefix

A wrapper can expose a second value through a property named projectedValue. The caller reaches it by prefixing the property name with a dollar sign: $health. The projection is a place to put extra information or helper operations that do not belong in the wrapped value itself. SwiftUI uses it to hand out Bindings: $name is the binding and name is the string.

Swift projectedValue exposes extra information

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

account.email is the plain String. account.$email is whatever projectedValue returns, here the wrapper itself, so you can read rejectedAttempts. The projected value can be any type: a Bool ("is the value valid?"), a Publisher, a Binding, or a struct with helper methods. Without a projectedValue property, $name does not exist.

A second wrapper: trimming text

One more example, to show that wrappers are not only for numbers. Trimmed removes leading and trailing whitespace on every assignment. Whitespace trimming uses trimmingCharacters, which is part of Foundation on Linux, so the example imports it.

Swift A Trimmed wrapper for strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because Contact has a wrapper on a property without a default (name), its memberwise initializer requires name:. For city, the default " Berlin " is trimmed on construction, so the output shows [Berlin].

Wrappers on local variables

Since Swift 5.4 a property wrapper can also be applied to a local variable inside a function. That is handy to reuse the same rule outside of types:

Swift A wrapper on a local variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The energy climbs from 2 to 5, 8 and then stops at 10, and the reset to -100 ends at 0, with no if statements in the function.

Rules, limits and compiler errors

Property wrappers are powerful, but they come with restrictions. Seeing the errors makes them easy to remember.

A wrapper requires var. Because the hidden storage is mutated through the setter, you cannot wrap a let constant.

Swift A wrapper on a let (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler says property wrapper can only be applied to a 'var'. Change let to var.

The wrapped value type must match. The type of the property and the type of wrappedValue have to be compatible:

Swift Wrong wrapped type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Here the property is a Double but the wrapper holds an Int, so the compiler reports property type 'Double' does not match 'wrappedValue' type 'Int' (and, because it also tries to convert the default value, cannot convert value of type 'Double' to specified type 'Int'). A generic wrapper (Clamped<Value>) avoids this by adapting to the property's type.

More restrictions to remember:

  • No wrappers on computed properties or lazy properties, because there is no storage to wrap.
  • One wrapper per property by default. Composition is possible (@A @B var x), applied from the inside out, but it makes the code harder to read. Prefer one wrapper that does the whole job.
  • The wrapper can hurt Codable and equality. Synthesized Codable, Equatable and Hashable for a struct with wrapped properties use the wrapper type. A custom wrapper must itself conform (for example extension Clamped: Equatable where Value: Equatable) if you want these to be synthesized.
  • Wrappers cannot access the enclosing object by default. A wrapper that needs to know about its owner (for example, to notify it) uses a special static subscript subscript(_enclosingInstance:wrapped:storage:), which is advanced and works only on classes.
  • Hidden cost. Each wrapped property adds a wrapper instance. For a Clamped that stores a range, that doubles the storage for the property. In very large arrays of structs, this matters.
  • Concurrency. A wrapper type used across tasks must be Sendable. A struct with plain values is automatically so.

When to use a property wrapper

Wrappers are best for a rule that attaches to a property and repeats: validation, clamping, trimming, lazy loading from some store, thread-safe access, or observation. They are a poor fit when:

  • the rule applies only once (a didSet is simpler),
  • the logic depends on several properties at once (a method or a custom initializer expresses that better),
  • readers would be surprised by magic: a @Trimmed name that also silently capitalizes it breaks expectations.

Keep each wrapper small, named for what it guarantees, and document the guarantee in one line.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the only requirement of a type marked @propertyWrapper?

    wrappedValue is the property that reads and writes go through. Everything else, such as projectedValue and initializers, is optional.
  2. 2. Given @Clamped(0...10) var energy = 5, what does the 5 do?

    The default value after the equals sign is passed to the wrapper's init(wrappedValue:), and the arguments in parentheses go to the other initializer parameters.
  3. 3. What does person.$name return?

    The dollar prefix accesses the projected value. If the wrapper has no projectedValue property, $name does not exist.
  4. 4. Which declaration is rejected by the compiler?

    A property wrapper can only be applied to a var, because the setter of the hidden wrapper storage must be able to mutate it.
  5. 5. What is the hidden stored property for @Percentage var volume called inside the type?

    The compiler synthesizes a private property named with an underscore prefix that holds the wrapper instance. The dollar name is the projected value.

Summary

  • A property wrapper is a type marked @propertyWrapper with a wrappedValue; it lets you write a get/set rule once and attach it to many properties.
  • The compiler adds a hidden stored property _name holding the wrapper; the initial value goes to init(wrappedValue:).
  • Arguments in the attribute (@Clamped(0...100)) go to additional initializer parameters; generic wrappers adapt to the property type.
  • projectedValue is reachable as $name and is the place for extra information or operations.
  • Wrappers can be used on local variables, but only on var properties with storage, not on computed or lazy ones.
  • Synthesized Codable, Equatable and Hashable use the wrapper type, so give custom wrappers the right conformances.
  • Use wrappers for small, repeated, well-named rules; prefer plain code when the logic is used once or involves several properties.

Next: Result Builders