Demystifying data flow through SwiftUI
--
The newly released SwiftUI allows you to write your interface declaratively. And with the new data flow mechanisms, you can write your data flow declaratively as well — and everything will update as you would expect it to, automatically. The concepts are powerful, but they can be a little confusing.
In this post, I’ll break down all the ways to move data declaratively through our SwiftUI views. Let’s start with a cheat sheet, and then we’ll move into descriptions and examples of each.
Property
Summary: read-only values provided by the parent view.
- A property is how a view defines what it expects its parent view to give to it in order for it to render, like a
prop
in React. - These values are read-only. But when they change, SwiftUI automatically re-renders your view.
- Can have a default value, allowing a parent view to not pass its own value for the property.
Use when: Your view needs to simply render using a piece of data or state which the parent has, and that it does not need to modify.
Example: Here is an example, where a ContactAvatar
component is made to reuse the code that formats the image, and different images can be passed to it using a property.
@State
Summary: Internal, read-write values.
- A @State value is a source of truth managed internally to a view.
- Should be marked as private for idiomatic accuracy.
- Must have a default value which is used initially.
- When it is updated, the view will be re-rendered accordingly.
Use when: Your view component needs its own state; a piece of data which it can change, and which none of its parent views care about, such as a hover state.
Example: In this example, we have a NotificationCard
component which displays a long line of text. When it is clicked or tapped, it…