TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Changing property wrapper's properties

Forums > Swift

I want to make a property wrapper that stores 2 values: the current value and an old value. This is what I have so far:

@propertyWrapper struct DelayedValue<Value> {
    var currentValue: Value
    var oldValue: Value {
        didSet {
            currentValue = oldValue
        }
    }

    var wrappedValue: Value {
        get { return currentValue }
        set { currentValue = newValue }
    }

    var projectedValue: DelayedValue<Value> { self }

    init(wrappedValue: Value) {
        currentValue = wrappedValue
        oldValue = wrappedValue
    }
}

The problem that I'm having is that I can't set the oldValue on the wrapped property.

If I have a @DelayedValue @State private var offset = 0.0 and I try to do _offset.oldValue = 1 I get both "Cannot assign to property: 'self' is immutable" and "Cannot assign value of type 'Int' to type 'State<Double>'"

3      

If I now do:

@propertyWrapper struct DelayedState<Value> {
    @State var currentValue: Value
    @State var oldValue: Value {
        mutating didSet {
            currentValue = oldValue
        }
    }

    var wrappedValue: Value {
        get { return currentValue }
        mutating set { currentValue = newValue }
    }

    var projectedValue: DelayedState<Value> { self }

    init(wrappedValue: Value) {
        _currentValue = State(initialValue: wrappedValue)
        _oldValue = State(initialValue: wrappedValue)
    }
}

And try to do:

@DelayedState private var offset = 0.0
...
offset = 100

I now get this new error: "Cannot assign to property: 'self' is immutable"

3      

Some background: I am trying to "freeze" a view as described here and I think this kind of property wrapper could help me do just that.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.