Marco Eidinger
Swifty Tech by Marco Eidinger

Swifty Tech by Marco Eidinger

Make your SwiftUI view modifiers safer

Make your SwiftUI view modifiers safer

Marco Eidinger's photo
Marco Eidinger
Β·May 27, 2022Β·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Is something wrong with this code?

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            padding()
    }
}

Look closer 🧐

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            padding() //<-- missing the "."
    }
}

Typo alert ! 😲

The code will compile, but it will crash the app! Why?

Despite the missing qualifier, the code compiles because padding() gets treated as self.padding(). During runtime, that leads to an infinitely recursive View => stack overflow πŸ’₯

I did not find a technique to detect the mistake of a missing dot when using standard SwiftUI view modifiers other than ...

constant-vigilance.jpeg

But for custom view modifiers there is a simple way. We can use the Swift attribute @warn_unqualified_access to warn us in Xcode :)

According to the Swift documentation:

Apply this attribute to a top-level function, instance method, or class or static method to trigger warnings when that function or method is used without a preceding qualifier, such as a module name, type name, or instance variable or constant. Use this attribute to help discourage ambiguity between functions with the same name that are accessible from the same scope.

To better illustrate the use I am taking Apple's example of a custom modifier that you can use to create blue caption text surrounded by a rounded rectangle:

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 {
    @warn_unqualified_access //<-- produces a warning in Xcode if called without "." 
    func borderedCaption() -> some View {
        modifier(BorderedCaption())
    }
}

By adding @warn_unqualified_access to the function declaration of the View extension, Xcode is able to produce a warning whenever the function is called without the dot.

warning.png

This article is greatly inspired by Federico Zanetello's article which taught me about the existence and usefulness of @warn_unqualified_access.

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!

See recent sponsors |Β Learn more about Hashnode Sponsors
Β 
Share this