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]]
}

   

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.