Yes, SwiftUI modifiers are implemented as functions. Most are on the View
protocol, but there are some that only apply to certain types of View
, like Text
.
padding(_:_:)
is a modifier on the basic View
protocol, so it can apply to any type of View
.
Something like strikethrough(_:color:)
is only implemented on the Text
type of View
.
You can see this most clearly when you create your own custom modifiers. The process involves creating a struct that conforms to the ViewModifier
protocol. It is then applied using the modifier(_:)
function on View
. But you can also extend View
with a custom function to apply your modifier.
From Apple's docs:
struct BorderedCaption: ViewModifier {
func body(content: Content) -> some View {
content
.font(.caption2)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 15)
.stroke(lineWidth: 1)
)
.foregroundColor(Color.blue)
}
}
extension View {
func borderedCaption() -> some View {
modifier(BorderedCaption())
}
}
//then in a View...
Text("Downtown Bus")
.borderedCaption()
So you can see that .borderedCaption()
is a function on View
. Built-in modifiers are implemented the same way.
You don't have to create a custom function by extending View
; you could just use .modifier(BorderedCaption())
instead. But it's cleaner the other way.