DevPrep

All topics › Modern Swift

What is a property wrapper?

Middle PRO

The idea

A property wrapper is a type marked @propertyWrapper that encapsulates storage and access logic for a property. The compiler rewrites @Wrapper var x into a hidden stored property _x: Wrapper and a computed property x that reads/writes _x.wrappedValue. If the wrapper has a projectedValue, it is available as $x.

@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) }
    }
    var projectedValue: ClosedRange<Value> { range }   // available as $health
}

struct Player {
    @Clamped(0...100) var health = 120
}
var player = Player()
print(player.health)                   // 100
player.health = -5
print(player.health, player.$health)   // 0 0...100

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store