SwiftUI: Views vs. Modifiers

KD Knowledge Diet
1 min readMar 20, 2024

SwiftUI, Apple’s modern UI framework, offers a fascinating way to build user interfaces. It treats views as data, enabling flexible UI development. But have you ever wondered when to use views or modifiers? Let’s explore this with a concise example.

Views: The Traditional Approach

Consider a `FeaturedLabel` view that adds a star image before text and applies styling:

struct FeaturedLabel: View {
var text: String
var body: some View {
HStack {
Image(systemName: "star")
Text(text)
}
.foregroundColor(.orange)
.font(.headline)
}
}

Modifiers: A Concise Alternative

The same result can be achieved using a modifier-like extension:

extension View {
func featured() -> some View {
HStack {
Image(systemName: "star")
self
}
.foregroundColor(.orange)
.font(.headline)
}
}

Now, in your `ContentView`, you can use both approaches:

struct ContentView: View {
var body: some View {
VStack {
FeaturedLabel(text: "Hello, world!")
Text("Hello, world!").featured()
}
}
}

Choosing Between Views and Modifiers

The choice between views and modifiers often depends on the structure of your UI:

- Use views when you need a clear hierarchy or layout changes.
- Use modifiers for style adjustments or single-view enhancements.

In the end, SwiftUI empowers you to create stunning user interfaces with flexibility, whether you opt for views or modifiers.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!