When to Use Structs, Computed Properties, and Functions in SwiftUI for View Creation
Discover how to effectively use Structs, Computed Properties, and Functions in SwiftUI to create efficient, reusable, and organized UI components, ensuring clean and maintainable code for complex view structures.
TL;DR #
Structs are ideal for self-contained and reusable components.
Computed Properties help organize complex views within the same struct.
Functions are best for parameter-driven or conditional view creation.
Structs #
- Use Structs for reusable and standalone UI components.
- Each struct has its own
bodythat defines how the view looks.
Example: AvatarView
struct AvatarView: View {
var image: Image
var size: CGFloat
var borderColor: Color
var borderWidth: CGFloat
var body: some View {
image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: size, height: size)
.clipShape(Circle())
.overlay(
Circle()
.stroke(borderColor, lineWidth: borderWidth)
)
}
}
Computed Properties #
- Use Computed Properties within a single view to break down complex layouts.
- Keep your view code organized and readable by grouping related subviews.
Example: ContentView with Subviews
struct ContentView: View {
var body: some View {
VStack {
header
Divider()
mainContent
Spacer()
}
.padding()
}
var header: some View {
VStack(alignment: .leading, spacing: 5) {
title
subtitle
}
}
var title: some View {
Text("Welcome to SwiftUI")
.font(.largeTitle)
.fontWeight(.bold)
}
var subtitle: some View {
Text("Building complex UIs with ease")
.font(.subheadline)
.foregroundColor(.gray)
}
var mainContent: some View {
Text("Main content goes here.")
.padding()
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(8)
}
}
Functions #
- Use Functions when you need to generate views based on parameters or apply conditional logic.
Example: Dynamic Label Creation
struct ContentView: View {
var body: some View {
VStack {
createLabel(text: "Hello, World!", isHighlighted: true)
createLabel(text: "SwiftUI Functions", isHighlighted: false)
}
.padding()
}
func createLabel(text: String, isHighlighted: Bool) -> some View {
Text(text)
.padding()
.background(isHighlighted ? Color.yellow : Color.gray)
.cornerRadius(8)
.foregroundColor(isHighlighted ? .black : .white)
}
}