View builder formatting

Hi everyone :waving_hand:

I’m using Apple’s swift-format to keep my Swift code tidy, and I’d love to achieve a visual style where there’s one blank line between consecutive components inside a @ViewBuilder — for example:

var body: some View {
    VStack {
        Text("Hello")

        Image(systemName: "star")

        Button("Tap") {}
    }
}

But without adding newlines at the start or end of the block.

Currently, it seems swift-format doesn’t have a built-in rule or configuration that can insert blank lines between statements, only around declarations or after imports.

Before hacking together a regex post-processor, I wanted to ask:

  • Is there any ongoing work or planned rule in swift-format to support spacing between expressions (like ViewBuilder components)?

  • Has anyone experimented with custom rule support or an API for registering extra rules at runtime?

  • Would such a feature be acceptable as a contribution (e.g. a BlankLineBetweenStatementsInViewBuilder rule)?

This kind of spacing makes SwiftUI code far more readable in larger body views, so I imagine others might be interested too.

Thanks in advance for any pointers or design guidance!
— Nick

Setting aside the specifics of the desired format itself, there's no way for a tool like swift-format to know specifically that a particular code block is in a ViewBuilder (or any result builder) context. That's semantic information that comes from the definition of the body property on the View protocol, which we don't have access to; we can only see the contents of a single source file at a time.

Yes, there are heuristics we could probably use to guess whether it's a ViewBuilder, but we're not terribly interested in trying to implement those because they're often wrong as much as they're right.

1 Like

Fair. Any other solutions to this though?

It surely can’t be that there will never be a solution for a quite fundamental Swift feature.