Home > front end >  How to use optional @State variable with binding parameter in SwiftUI
How to use optional @State variable with binding parameter in SwiftUI

Time:12-15

I am trying to use an optional @State variable with a TextField. This is my code:

struct StorageView: View {
    
    @State private var storedValue: String?
    
    var body: some View {
        VStack {
            TextField("Type a value", text: $storedValue)
        }
        
    }
}

When I use this code, I get the following error: Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'

I have tried the following code for both the values to be optional, but nothing seems to work:

TextField("Type a value", text: $storedValue ?? "")
TextField("Type a value", text: Binding($storedValue)!)

How would I go about using an optional @State variable with a binding? Any help with this is appreciated.

CodePudding user response:

How would I go about using an optional @State variable with a binding? Any help with this is appreciated.

It looks like you are using an optional state variable with a binding. You get an error because TextField's initializer expects a Binding<String> rather than a Binding<String?>. I guess you could solve the problem by adding another initializer that accepts Binding<String?>, or maybe making an adapter that converts between Binding<String?> and Binding<String>, but a better option might be to have a good think about why you need your state variable to be optional in the first place. After all this string something that will be displayed in your UI -- what do you expect your TextField to display if storedValue is nil?

  • Related