0

How do you unwrap an optional @State to be used as a binding parameter?

import SwiftUI

struct ContentView: View {
    @State var testString = "Hello"
    var body: some View {
        TestView(test: testString)
    }
}

struct TestView : View {
    @State var test : String?
    var body: some View {
       TextField("Test", text: $test)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Here is the compiler error I receive on the TextField call.

Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'
  • 1
    https://stackoverflow.com/questions/57021722/swiftui-optional-textfield – cora Dec 26 '20 at 17:59
  • Your question looks incorrect, did you mean for testString in ContentView to be optional and test in TestView to be declared as @Binding and not @State? – Joakim Danielson Dec 26 '20 at 18:23

2 Answers2

1

In such case we should use Binding

struct ContentView: View {
    @State var testString = "Hello"
    var body: some View {
        TestView(test: $testString)
    }
}

struct TestView : View {
    @Binding var test : String
    var body: some View {
       TextField("Test", text: $test)
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Yes, but I need the argument to be optional to the TestView. – Kevin McQuown Dec 26 '20 at 18:16
  • Scenario shown in question did not depict that, you have to provide more realistic code if you want exact answer. Note, reference provided by @cora gives many possible variants to be adapted with this answer to avoid duplications. – Asperi Dec 26 '20 at 18:25
0

Here is the one line solution which appears to work.

TextField("Test", text: Binding($test)!)

So new struct is like this

struct TestView : View {
    @State var test : String?
    var body: some View {
        VStack {
            TextField("Test", text: Binding($test)!)
            Text(test!)
        }
    }
}
  • And what is the value of testString in ContentView once you have entered some text in the text field in this view? – Joakim Danielson Dec 26 '20 at 18:45
  • The value in ContentView will not change, but that was fine in my example. I was just trying to get an optional passed in to be used in another view that needs a binding value. – Kevin McQuown Dec 26 '20 at 18:59