Swift Property Wrappers

Property Wrappers are another syntactic-sugar that you let you dictate how properties are get defined and stored. Without going into theoretical exposition let us start using propertyWrapper

@propertyWrapper
struct AssignmentCounter<V> {
    private var value: V
    private var assignmentCount: Int = 0
    init(wrappedValue val: V) {
        value = val
        wrappedValue = val
    }
    var wrappedValue: V {
        set {
            assignmentCount += 1
            value = newValue
        }
        get {
            return value
        }
    }
}

The property wrapper’s job is to keep track of how many times it has been assigned to.

struct Example {
    @AssignmentCounter var data: Int = 10
    mutating func increment() {
        data += 1
    }
}
let ex = Example()
ex.increment()
ex.increment()
ex.increment()

Everything seems to work pretty well here. Only one problem, how will we know how many times data was assigned. But accessing the information regarding how many times data has been assigned doesn’t seem to be possible. Property wrappers provide a way for this with projectedValue and $ operator. Lets add one computed value to AssignmentCounter.

@propertyWrapper
struct AssignmentCounter<V> {
    private var value: V
    private var assignmentCount: Int = 0
    init(wrappedValue val: V) {
        value = val
        wrappedValue = val
    }
    var wrappedValue: V {
        set {
            assignmentCount += 1
            value = newValue
        }
        get {
            return value
        }
    }
    var projectedValue: AssignmentCounter { self }
}

Now we can access the AssignmentCounter type instead of the type it wraps.

extension Example {
    func inspect() -> Int {
        return $data.assignmentCount
    }
}

So, thats my short post on property wrappers.

Things to remember