In a Swift property wrapper, what is projectedValue, and how do $volume and _volume differ from volume?
answer
- an optional second channel
- dollar sign for the projection
- underscore for the wrapper instance
- access level of each synthesized name
basics
~10 sprojectedValue is an optional property a wrapper declares to expose extra information; Swift surfaces it as $volume with volume's access level. volume forwards to wrappedValue, and _volume is the private wrapper instance itself.
solid answer
~40 s`projectedValue` is an optional instance property on the wrapper type, and the compiler exposes it as `$volume` with the same access level as `volume`. Its type is whatever the author chooses: a flag, a helper type, or `self`. In my clamped volume, `projectedValue` is a `Bool` that says whether the last write was clamped, so after `volume = 140` I read `volume == 100` and `$volume == true`. `volume` itself forwards to `_volume.wrappedValue`, and `_volume` is the stored wrapper instance, always `private`, so only the declaring type can reach it. If the wrapper declares no `projectedValue`, there is no `$volume`; if the projection has no accessible setter, `$volume` is read-only.
code
swift · 29 lines@propertyWrapper
struct Clamped {
private var value: Int
private let range: ClosedRange<Int>
private(set) var projectedValue = false // true when the last write was clamped
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
var wrappedValue: Int {
get { value }
set {
value = min(max(newValue, range.lowerBound), range.upperBound)
projectedValue = value != newValue
}
}
}
struct AudioSettings {
@Clamped(0...100) var volume = 50
}
var settings = AudioSettings()
settings.volume = 140
print(settings.volume, settings.$volume) // Prints "100 true"
settings.volume = 30
print(settings.volume, settings.$volume) // Prints "30 false"go deeper
Recall that $name reads a wrapper's projection and that not every wrapper has one.
Explain the three synthesized names, their types and access levels, and how projectedValue's type and setter decide what $volume is and whether it is writable.
Use projections deliberately: choose what a wrapper exposes through $ versus keeping it in private _ storage, and know the extension and composition limits on which projection is synthesized.
Weigh the readability cost of $ names whose meaning differs per wrapper when setting team conventions for custom wrappers in shared code.
## Three names for one wrapped property When a wrapper declares a `projectedValue`, one wrapped property gives you three names. For `@Clamped(0...100) var volume = 50` inside `AudioSettings`: | Name | What it is | Type | Access | |---|---|---|---| | `volume` | computed property forwarding to `_volume.wrappedValue` | `Int` | the property's own access level | | `$volume` | computed property forwarding to `_volume.projectedValue` | whatever `projectedValue` returns, here `Bool` | the property's own access level | | `_volume` | the stored wrapper instance | `Clamped` | always `private` | The **wrapped value** is what callers normally see. The **projected value** is a second, optional channel the wrapper author designs to expose extra information or API. The **backing storage** is the wrapper instance itself and stays hidden inside the declaring type. ## Declaring a projection A wrapper opts in by declaring an instance property named `projectedValue` directly in the wrapper type: - It can have **any type**: a `Bool` flag, a separate API type, or `self` to hand out the wrapper instance. - It must have the **same access level as the wrapper type**, like `wrappedValue`. - It must be declared **in the type's own body**. A `projectedValue` added in an extension does not produce a `$` name; the compiler reports that the containing type has no member `$volume`. - If `projectedValue` is get-only, or its setter is inaccessible such as `private(set)`, then `$volume` is read-only and `settings.$volume = true` fails with `cannot assign to property: '$volume' is immutable`. - With no `projectedValue` at all, there is simply no `$volume`. ## The clamped volume, step by step In the code example, `Clamped` keeps the number inside a range and records whether the last write had to be adjusted: 1. `settings.volume = 140` calls the synthesized setter, which assigns `_volume.wrappedValue = 140`. 2. `Clamped`'s setter stores `min(max(140, 0), 100)`, which is `100`, and sets `projectedValue` to `true` because the stored value differs from what was written. 3. `settings.volume` reads `100`; `settings.$volume` reads `_volume.projectedValue`, which is `true`. 4. `settings.volume = 30` fits the range, so the setter stores `30` and resets the flag to `false`. The caller learns that clamping happened without the wrapper widening `volume`'s own type to something like a tuple. ## Using `$` and `_` inside the type Inside the declaring type you can drop `self.` before both names, exactly as with other properties. `$volume` is the public face of the extra channel; `_volume` lets the type replace the whole wrapper, for example to reset the volume and its flag in one assignment: ```swift extension AudioSettings { mutating func resetVolume() -> Bool { let wasClamped = $volume // the projection; no self. needed _volume = Clamped(wrappedValue: 50, 0...100) // the private wrapper instance return wasClamped } } ``` From outside the type, `_volume` is out of reach because it is `private`, while `$volume` is visible to anyone who can see `volume`. ## Rules around the `$` prefix - Only the compiler can create `$`-prefixed members. Declaring your own `$volume` fails with `cannot declare entity named '$volume'; the '$' prefix is reserved for implicitly-synthesized declarations`, so a projection never collides with a property you write. - When several wrappers are stacked on one property, only the **outermost** wrapper's `projectedValue` becomes `$name`. - The meaning of `$` is entirely the wrapper author's choice. Two wrappers can project completely different things, so `$` tells you that a projection exists, never what it holds. ## Choosing what to project Wrapper authors tend to pick one of three shapes, and the choice is part of the wrapper's API: - **A status value**, like the `Bool` here: cheap, read-only, and it answers one question about the last write. - **A separate helper type** that offers a narrow set of operations, for example a type with a `reset()` method, so callers get exactly the extra API the author intends. - **`self`**, which hands out a copy of the wrapper (or, for a class wrapper, a reference to it) with everything its access level allows. Whatever the shape, `volume` keeps its plain `Int` type, so code that never touches `$volume` is unaffected. ## Common mistakes - Assuming `$volume` is always the wrapper itself; it is whatever `projectedValue` returns. - Assuming every wrapper has a `$` name; only those that declare `projectedValue` do. - Treating `_volume` as part of the type's API; it is private storage.
- Can code outside AudioSettings assign to $volume?Only if `projectedValue` has a setter that is accessible. Here it is declared `private(set)`, so the synthesized `$volume` has no usable setter and `settings.$volume = true` fails with `cannot assign to property: '$volume' is immutable`. A wrapper that wants writable projections declares a settable `projectedValue` with the wrapper's access level.
- Why do many wrappers return self as their projectedValue?Returning `self` hands callers the wrapper instance, so they can call its methods or read its configuration, while the backing `_volume` stays private. It gives the wrapper's API a public face without exposing storage the declaring type controls.
- What happens if the wrapper adds projectedValue in an extension instead of its body?No `$` name is synthesized. The compiler only looks for `projectedValue` declared directly in the wrapper type, so `settings.$volume` fails with `value of type 'AudioSettings' has no member '$volume'`.
- $volume always returns the wrapper instance itself.
- Every property wrapper gives you a $ name automatically.
- _volume has the same access level as volume.
- You can declare your own $volume property to customize the projection.
- The projected value must have the same type as the wrapped value.