Home > Enterprise >  Map Binding<SomeType?> to Binding<Bool>
Map Binding<SomeType?> to Binding<Bool>

Time:02-07

I have this line of code in my View:

@State private var selectedConversation: DbConversation? = nil

And this:

// views...
.confirmationDialog(
    "text",
    isPresented: $selectedConversation != nil,
    titleVisibility: .hidden
)

but this gives an error. I was wondering if I can show a confirmationDialog when I fill selectedConversation somewhere in my view.

Is there a solution which does not require my updating 2 property? I mean I can create a Binding and set that to true and fill selectedConversation, but that are 2 steps.

CodePudding user response:

You can define Binding property and wrap your State property:

private var isPresented: Binding<Bool> {
    Binding(
        get: { selectedConversation != nil },
        set: { value in
            if !value {
                selectedConversation = nil
            }
        }
    )
}

CodePudding user response:

You can have a second property that you update in didSet that you use for isPresented

@State private var selectedConversation: DbConversation? = nil {
    didSet {
        isSelected = selectedConversation != nil
    }
}
@State var isSelected = false
  •  Tags:  
  • Related