A Beginners Guide to Views in SwiftUI
Understand this
3 min readDec 4, 2024
A view in SwiftUI is a lightweight, transient object designed to be thrown away when the source for it is changed.
Unlike views in UIKit, SwiftUI views are not intended to be permanent or manually updated and instead of recomputed dynamically whenever the underlying data changes.
Views as Value Types
Views in SwiftUI are all struct
, which means they are value types.
These views have advantages:
struct
are lightweight and performant- Views are immutable making them predictable and easy to reason about
The View Protocol
All SwiftUI views conform to the View
protocol which requires a single computed body property that describes the view’s content.
Here is a minimal example of a SwiftUI view:
struct MyView: View {
var body: some View {
Text("Hello, SwiftUI!")
.padding()
}
}
Note that the view is composed of another view ( Text(“Hello, SwiftUI!”)
is another view)