TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Data flow between classes in SwiftUI

Forums > SwiftUI

You have a nested observable object.

class ClassB: ObservableObject {
    @Published var board: [[ClassC]]
}

class ClassC: ObservableObject {
    @Published var color: Color = .white
}

A limitation of SwiftUI is that it won't detect changes to nested observable objects. In your case the changes to the color property in ClassC will not be update board in ClassB. This is a common problem people run into in SwiftUI. If you enter SwiftUI nested observable object in a search engine, you will find many articles about the problem with nested observable objects and strategies for dealing with the problem.

The solution in your code is relatively simple. Since ClassC only contains a color, you can make board an array of Color arrays and get rid of ClassC.

class ClassB: ObservableObject {
    @Published var board: [[Color]]
}

   

One possible solution is to keep the view model as a class, and make A, B, and C structs. You would have only one observable object in this case, eliminating the nested observable object problem. But I don't know what your project needs from a data standpoint so I can't guarantee that converting the classes to structs will work for you. You may need A, B, and or C to be classes.

I also recommend entering the phrase SwiftUI nested observable object in a search engine. You will find Stack Overflow questions from people who had the same problem you have. You will also find articles about the problem with nested observable objects and strategies for dealing with the problem.

   

to OP: Rape is not a joke. Do you think such "jokes" make women feel more or less welcome in this community? I beg you to create an account with a different name. Thank you.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.