Understanding SwiftUI — Why are Views in SwiftUI Struct and not Class?

Shivam Maggu
2 min readFeb 28, 2023

In this 2nd article on Understanding SwiftUI, let’s discuss how views work in SwiftUI.

Table of Contents

  1. Why SwiftUI prefers Struct over Class?
  2. SwiftUI Views versus UIKit Views

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 @State, @ObservableObject and 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 body the 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.

SwiftUI Views versus UIKit Views

Originally published at https://blog.shivammaggu.com.

--

--

Shivam Maggu
0 Followers

iOS developer specializing in swift and anything tech that piques my interest.