17

I get the following error:

Cannot assign value of type 'Binding' to type 'String'

How to fix it? Please help.

struct TextFieldWithClear: View {
    var title: String
    @Binding var text: String
    
    init(_ title: String, text: Binding<String>) {
        self.title = title
        self.text = $text // ERROR: Cannot assign value of type 'Binding<String>' to type 'String'
    }
    
    var body: some View {
        HStack {
            TextField("Title", text: $text)
            Image(systemName: "xmark.circle.fill")
                .onTapGesture { text = "" }
        }
    }
}

2 Answers 2

48

Replace:

self.text = $text

with:

self._text = text

You need to inject the value of text into the wrapped value of self.text. The underscore "opens" the Binding for you to change its wrapped value. Don't need to use $ in your initializer.

Sign up to request clarification or add additional context in comments.

2 Comments

Interestingly, we have to use the generated _text: Binding<String>, rather than the text we defined.
a shame that if You choose "Generate Memberwise Initializer" it fails creating a correct inti for "Bound" vars.
-1
struct TextFieldWithClear: View {
    let title: String
    @Binding var text: String
    
    var body: some View {
        HStack {
            TextField("Title", text: $text)
            Image(systemName: "xmark.circle.fill")
                .onTapGesture { text = "" }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.