Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: Binding in initializer: default value

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading