1

I have a UserService class with an optional user variable.

struct User: Codable {
    var id, first_name, last_name, dob: String
}

class UserService : ObservableObject {
    @Published var user: User?
}

I pass this object from a view to another view in NavigationLink.

NavigationLink(destination: EditProfileView(userService: userService).navigationBarBackButtonHidden(true), isActive: $editProfileScreenActive){
                    Text("")
                }

In EditProfileView I was not able to use the properties of User in TextField. e.g.

TextField("first_name", text: $userService.user?.first_name)

I tried different approaches but was not able to pass first_name as a binding to TextField. I am getting different kinds of compilation errors.

Any suggestions how to fix this? (I am not an experienced swift programmer :) )

BadSeed
  • 11
  • 2

2 Answers2

0

As the user is optional and TextField expects a non optional String as the text parameter, you have to first check if the user is not nil.

if let user = Binding($userService.user) {
    TextField("first_name", text: user.firstName)
}

However, if you still want to have a text field when the user is nil (this depends on what you are trying to achieve on this screen, I cannot determine this from your question), you might simply want to have an @State variable that you initialise with the users first name.

Steven
  • 419
  • 4
  • 6
-1

Check by making a shared let, equal to User. Like this:

struct User: Codable {
    static let shared = User()
    var id, first_name, last_name, dob: String
}

So now you only have to type User.shared.propertyName

Swifter64
  • 5
  • 3