skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 = "" }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search