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>?

Terms of Service

Privacy Policy

Cookie Policy