Understanding Data Flow in SwiftUI

Understanding Data Flow in SwiftUI

Changing data in a SwiftUI view can make your UI update automatically. It almost seems like magic. But there’s no magic here, only a sleight of hand known as data flow.

[…]

By the time you’re done, you’ll feel much more comfortable putting data into your views in SwiftUI.

[…]

Open UserView.swift. Replace the contents of the file with the following:

[…]

Every time your data triggers an update in a view, SwiftUI recalculates the view’s body, thereby refreshing the view. When this happens, if you have an @ObservedObject declared in your view, SwiftUI recreates that object when your view refreshes.

[…]

Build and run. You’ll see the same behavior as before, but now, SwiftUI manages the lifecycle of movieStore.

[…]

Open UserView.swift. At the top of the view, add this line after the one which defines userName:

[…]

Create a new view in Xcode by going to File ▸ New ▸ File… in the menu bar. Select Swift File and click Next. Name it UserInfo.swift and click Create. Replace the contents with this:

UserInfo is a Swift struct that represents a user. Next, create another file in the same manner. Name this one UserStore.swift. Replace its contents with the following:

[…]

Sometimes, your data’s source of truth doesn’t live inside a SwiftUI view. In this case, use the ObservableObject protocol to allow a class to interact with SwiftUI. An ObservableObject is a source of truth that sends updates to a SwiftUI view, and it receives updates based on changes to the UI.

[…]

In SwiftUI, the environment is a store for variables and objects that are shared between a view and its children.

[…]

In UserView.swift, add this line along with the rest of the property declarations:

[…]

Open AddMovie.swift. Add the following code near the top of the view, directly under the declaration of movieStore:

[…]

If you want to learn more about SwiftUI, including a whole chapter on data flow, then the SwiftUI by Tutorials book has what you need.

[…]