Skip to main content

After creating a new view with a @Binding string as follows

struct EditRival: View {

  @Environment(\.presentationMode) var presentationMode
  @EnvironmentObject var realmPerson: RealmPersons
  @Binding var uid: String

 

The previews struct had an error with the var previews

struct EditRival_Previews: PreviewProvider {

  //... Initial code ...//

  static var previews: some View {
    EditRival()
      .environmentObject(RealmPersons())
}

The error was Cannot convert value of type 'String' to expected argument type 'Binding<String>'

 

What is happening

What to do when you have a Cannot convert value of type 'String' to expected argument type 'Binding<String>'

This error occurs when you have attempted to create an interactive component without a binding, for example:

TextField("Enter your lastname", text: lastname)

How to fix, ensure your property is marked with @State, like this:

@State private var lastname = ""

Now create your component using a two-way binding, like this:

TextField("Enter your lastname", text: $lastname)

 

Prototyping / preview 

That is great, however in this instance we are in preview mode and we just need to pass a value in your SwiftUI code.  Subsequently, you will find it useful to use constant bindings.  Constant bindings are hard-coded values that don’t change, but can still be used like regular bindings so your code can be seen working in preview.

 

Applying this methodology to the initial problem

Once the uid binding variable was added to the struct, it needs to be added to the EditRival reference.  Nothing new here.  If you attempt to add an empty string such as "" applied as EditRival(uid: ""), the string / binding string error remains.  However, applying the constant mythology noted above will let the variable uid be tested.  Wrap the empty or initialisation call in a constant such as .constant("").  How is it applied:

static var previews: some View {

    //... Initial code ...// 

    EditRival(uid: .constant(""))
      .environmentObject(RealmPersons())
}

One of the key additions to the code above is .constant().  The uid noted above is a string, parsing an empty string is okay.  However, what happens if it is not empty.  For example,

TextField("FirstName", text: self.rival.firstName)

When this was first run, the binding error popped up.  Subsequently, wrapping this in a constant solved the binding issue.

TextField("FirstName", text: .constant(self.rival.firstName))