A property wrapper that is optional

Overview

I would like to define an optional @Binding property so that I can assign nil to the binding (not the wrapped value).

My Attempt:

  • I could use Binding<Int>? directly but I lose some of the conveniences that the property wrapper provides (I don't have to use wrappedValue and could it directly)

Question:

  • Is there a way to define an optional @Binding?

Code

import SwiftUI

class Car {
    
    @Binding var price: Int //I would like this Binding<Int>?
    //Is there anyway to use to do that using @Binding?
    
    init(price: Binding<Int>) {
        _price = price
    }
}

// Ideally I would like to the following:
//let car = Car(price: nil)

Note: Sorry this example pertains to SwiftUI but I think it could apply to other property wrappers as well.

You should be able to implement a custom property wrapper wrapping Binding<T>? and implementing semantics you need.

1 Like

Thanks @Nickolas_Pohilets I guess there is no built in mechanism to do it, will see if I can create custom property wrapper or settle for the Binding<T>?

Was this ever solved? I did not see anything new about this in WWDC this last week but was curious if you were able to implement a wrapper @somu

@ThorTheViking
It has been a while since I asked this question, so I don't remember why I wanted this.

I think you can still use Binding<Int>?, instead of @Binding

As far as propertyWrapper changes, I am not very sure as I have not gone through the Swift 5.5 Beta changes.

Terms of Service

Privacy Policy

Cookie Policy