blksld
blksld

Reputation: 139

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

I am new to SwiftUi and I got an Error which I can not fix. Basically, I want to change the name attribute of the AB class in the SettingsView.

Also, I got some questions which I hope anyone can answer.

  1. Do i have to make the class AB an ObservableObject with @Published attributes, when it is already in my User class as @Published attribute?
  2. Should the class AB be a struct? I am using the class User as an EnvironmentObject
class User: ObservableObject {
   @Published var name: String
   ...
   @Publsihed var ab: [AB]
   @Published var currentAb: AB?

   internal init(name: String, ab: [AB]) {
      self.name = name
      self.ab = ab
      self.currentAb = ab.first
   }
}
class AB: ObervableObject {
    @Published var name: String
    ...
}

I get the Error here because of TextField("new name", text: $user.currentAb.wrappedValue.name).

struct SettingsView: View {

@EnvironmentObject var user: User

var body: some View {
        Form { //Error: Unable to infer complex closure return type; add explicit type to disambiguate
           Section(header: Text("")) {
                TextField("new name", text: $user.currentAb.wrappedValue.name) // <- Error is shown here
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
        }
}

Thanks.

Upvotes: 6

Views: 17640

Answers (1)

Asperi
Asperi

Reputation: 258345

It is better to do by separating into different view, like

var body: some View {
        Form {
           Section(header: Text("")) {
               if user.currentAb != nil {
                  SomeNameView(vm: user.currentAb!)
               } else {
                  Text("any holder view here")
               }
            }
        }
}

and separated view

struct SomeNameView: View {
    @ObservedObject var vm: AB

    var body: some View {
       TextField("new name", text: $vm.name)
           .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}

Upvotes: 11

Related Questions