简体   繁体   中英

How to use optional @State variable with binding parameter in SwiftUI

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM