RESULT BUILDERS AND DSL — X — FILE

THE MAGIC

Probably you have already seen a piece of code like that, and you know where it does come from.

I STILL DON’ T UNDERSTAND HOW IT WORKS

Here is what happens using a ViewBuilder the heart of SwiftUI:

SwiftUI view builder
SwiftUI view builder at compile time

WHY SHOULD I USE THEM?

I think that they find a natural purpose when you need to compose something and when what you are building is the sum of different elements. For the very same reason they are very useful to write a DSL.
For instance imagine a tool to create a CI pipeline, instead of having weird indentation files for configuring it you can have a very well defined pipeline with compile time error reporting.

RESULT BUILDER ANATOMY

Result builder are built on to of three types (actually typealiased types):
- Component: basic building block
- Expression: when you want to make them work with different input types
- Final result: when you want to make builders work with a different type as the final result.

LET’ S CREATE A MARKDOWN(-ish) BUILDER

The document builder must support these tags:
- Level One header (# )
- Level Two header (## )
- Level Three header ( ### )
- Body

Some abstractions to make our Markdown editor
Our DSL objects
MarkdownDoc
Vanilla result builder implementation
Vanilla MarkdownDoc
A lot better markdown implementation
Builder method to add only IF statement
Builder methods to add IF-ELSE statement
Magic revealed
Builder methods to add FOR loops

FINAL THOUGHTS

Result builders are really an awesome feature and as applications growth in complexity they really help in simplifying creating configurations or anything that you can create with a specific DSL. They abstract away complexities and give back focus to the context, the domain and what you are trying to solve.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store