Ask Your Question
1

What is the method to set a default or nil value for @Binding in the initializer of a SwiftUI View?

asked 2023-07-04 22:47:35 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-04 23:16:02 +0000

lakamha gravatar image

To set a default or nil value for @Binding in the initializer of a SwiftUI View, you can use a property wrapper called @State. Here is an example:

struct MyView: View {
  @Binding var myBinding: Bool

  init(myBinding: Binding<Bool> = .constant(false)) {
    _myBinding = State<Bool>(initialValue: myBinding.wrappedValue)
  }

  var body: some View {
    // ...
  }
}

In this example, we use the @State property wrapper to store the initial value of our binding in the _myBinding property, which is then used as the source of our @Binding property. If no value is provided for myBinding when the view is initialized, we default to a constant value of false.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-04 22:47:35 +0000

Seen: 13 times

Last updated: Jul 04 '23