6

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.

1 Answer 1

12

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())
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works if i want the name of the User, but i want the name of the currentAb
I got your point - see updated with possible approach.
using the $.varName was the winner hear for me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.