Search code examples
swiftuiobservableobject

In SwiftUI, how to implement @Published class in the right way


In SwiftUI, I have a class for user data and I convert JSON data into it:

class UserData: Codable {
    var displayName: String
    var employeeId: String
    var firstName: String
    var lastName: String
    // more ...
}

by JSONDecoder().decode(UserData.self, from: jsonData)

And I have a class UserProfile holding the user data:

class UserProfile : ObservableObject {
  
    @Published var userData: UserData?

}

Now the problem is that, whenever I updated userData, like

userProfile.userData?.displayName = "New John"

the data change is not published to the view. I know the reason is because the userData is actually a class, so if I do

userProfile.userData = userProfile.userData after a value is newly assigned, the view gets updated.

My question is how to do it in the right way? I don't want to call userData = userData each time a value is updated, it doesn't sound right.


Solution

  • If you make UserData a struct, any changes to its properties will be published like you want.