In swiftui is there a way to pass a field of a propertywrapper that is an object, to a Binding parameter

I have a View that takes a Binding field of type String. I would like to pass the field of a propertywrapper that is an object. Is this possible?

@Binding var commentDto: CommentDto? // has a field called text
var body: some View {
    CustomTextField(text: $commentDto.text) // this gives error as field text, of $commentDto, is not available when using wrapper
}

Assuming that CommentDto looks something like this:

struct CommentDto {
  var text: String
}

then $commentDto.text will be Binding<String>, which I assume is not what you want. If you just want a String, you can do commentDto.text (no $).

PS

As per API design guidelines, it should be CommentDTO.

That is what I want actually, Binding<String>. But because the commentDto is optional compiler will not allow me to call $commentDto.text.

See this initializer. It allows you to provide custom closures that are called in order to get and set the value of the binding.

Terms of Service

Privacy Policy

Cookie Policy