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?>)
Small Talk
  • 747
  • 1
  • 6
  • 15
  • 1
    Do you mean `Binding.constant(true)`? – Sweeper Jul 18 '21 at 01: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. – jnpdx Jul 18 '21 at 01:54
  • @jnpdx, thanks, `@State var bool: Bool = true` appears to vend a `Binding` . I was trying to manually init a Binding with a wrappedValue to see if I understood how they get created. – Small Talk Jul 18 '21 at 04:04
  • 1
    Maybe this will be helpful for you. https://stackoverflow.com/questions/56973959/swiftui-how-to-implement-a-custom-init-with-binding-variables – shingo.nakanishi Jul 18 '21 at 05: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 – lorem ipsum Jul 18 '21 at 13:09
  • Hi, All these comments are spot on, and helped greatly with my understanding of bindings in general. I'm happy to marked answered if any of the respondents wants to summarize the above. – Small Talk Jul 19 '21 at 02:06

1 Answers1

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)
} 
Paul B
  • 3,989
  • 33
  • 46