0

How do I manually init a Swift Binding, with a desired wrapped value?

Using Bool as type, here is most basic desired init

let b: Binding<Bool> = Binding.init(true) //errors out with messages:

Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool?>

Value of optional type 'Binding<Bool>?' must be unwrapped to a value of type 'Binding<Bool>'

Questions I have

  1. Why does the above error out?
  2. What is the correct syntax to init a simple Bool binding
  3. Why must optionals be involved in the type signature (<'Binding<Bool?>)
6
  • 1
    Do you mean Binding<Bool>.constant(true)? Commented Jul 18, 2021 at 1:53
  • 3
    Binding.init(Boolean) isn't a value initializer for Binding. Can you elaborate on what you're trying to accomplish? A binding is usually used for two-way communication in SwiftUI or (possibly) Combine. Initializing a Binding without a @State or @Published property behind it (or something else that gets written to in a custom Binding) is suspicious. Maybe if you describe what you're trying to accomplish, someone can help you find a solution. Commented Jul 18, 2021 at 1:54
  • @jnpdx, thanks, @State var bool: Bool = true appears to vend a Binding<Bool> . I was trying to manually init a Binding<Bool> with a wrappedValue to see if I understood how they get created. Commented Jul 18, 2021 at 4:04
  • 1
    Maybe this will be helpful for you. stackoverflow.com/questions/56973959/… Commented Jul 18, 2021 at 5:05
  • 1
    A Binding is a two way connection it isn’t meant to be initialized without a source of truth. It has .constant to make a dead end for previews it is just a dead end as a source of truth Commented Jul 18, 2021 at 13:09

1 Answer 1

0

You rather need @State. If you want default initial value along with the opportunity to set it, consider this.

@State var a: Bool
init(initialA: Bool = true) {
    _a = .init(initialValue: initialA)
} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.