SwiftUI: Binding in initializer: default value

Advertisements

Consider the following example:

struct TestView: View {
    @Binding private var value: String
    init(value: Binding<String>) {
        self._value = value
    }
}

How can I initialize the TestView without any Binding, i.e. just bind it to an empty string (if the caller doesn’t need to connect that property)?

Ideally I’d be able to use the TestView like this (sometimes):

TestView()

I’ve tried setting a default value in the initializer, but obviously, it fails:

init(value: Binding<String> = Binding<Strings>("")) {

Any approaches on how to tackle this API issue?

>Solution :

Use the constant factory method:

init(value: Binding<String> = .constant("")) {
    self._value = value
}

Now you can do TestView().

Leave a ReplyCancel reply