In this 2nd article on Understanding SwiftUI, let’s discuss how views work in SwiftUI.
Table of Contents
Why SwiftUI prefers Struct over Class?
1. SwiftUI Views are structs instead of classes. This avoids having multiple inherited properties, keeps them lightweight and improves performance.
2. SwiftUI Views are passed by value. This avoids retain cycles and reference counting, leading to fewer memory leaks.
3. SwiftUI is based on the core principle of maintaining a Single Source of Truth.
- View rendering depends on properties like the
@ObservableObjectand so on. These are known as a Source of truth.
- When the value of these properties changes, the SwiftUI framework asks the view body to render the UI with the updated values.
- With UIKit, developers manage not only the state of the data but also the view changes based on that data. Whenever a view reads a piece of data, it creates a dependency between them. On data change, views should be updated to reflect the new value. When it fails to do so, then it becomes a bug. There can be multiple states in our app and multiple functions reacting to those state changes. If we do not maintain a source of truth for the current app state, UI bugs tend to creep in due to human error.
- SwiftUI tends to overcome this issue by making
bodythe only entry point. Despite the numerous states an app might find itself in, there is only one possible way to update the UI which is by rendering the view body. Views react to state changes by informing the framework. The framework then recomputes the derived values and generates the body with updated derived values.