Write Beautiful Code With Swift Result Builder | by Avi Tsadok | May, 2022

Make your UIKit codebases look as clear as SwiftUI

Probably the most noticeable factor about SwiftUI is that it seems unimaginable. It takes a comparatively huge chunk of code and squeezes it into one thing stunning and simple in order that even non-programmers can perceive what’s happening.

However do you know that beginning Swift 5.4, you possibly can replicate that have to something you need?

You may construct URL Requests, refined information buildings, and even a complete display screen in UIKit the identical approach you do in SwiftUI.

In different phrases, you possibly can implement DSL in your apps very simply.

If you happen to haven’t heard the time period “DSL”, it’s time to speak about it.

DSL stands for Area-Particular Language.

However what does it imply?

Once we have a look at a “common” programming language, for instance — Swift, we will see that theoretically, we will construct something we would like.

All of it depends on the framework we’ve got beneath.

For instance, we will construct server-side functions, internet, and Android if solely we could have the correct framework.

Lessons, structs, and Enums will not be iOS-specific options.

However, a DSL is a language written to take care of a particular area or an issue.

One good instance is HTML.

HTML’s major objective is to explain a doc displayed on an online web page.

HTML is superb for that function and may simply be learn by non-programmers.

One other instance is XML or JSON, that are nice for holding a basic information construction.

Going again to Swift — SwiftUI is a DSL. Its major function is to explain a dynamic display screen, and it’s additionally constructed on prime of Swift, which is a GPL (general-purpose language).

To create extra DSL-style code, we have to use one thing referred to as Consequence Builder, which is a part of Swift Language and can assist us create stunning code.

Let’s attempt to perceive how Consequence Builder works utilizing an instance, and we’ll go along with a simple one — information construction.

Assuming we wish to describe a knowledge construction constructed from Workforce and Participant.

Our information construction could look one thing like that:

That’s an ordinary code snippet of structs.

Do you see all of the brackets? That’s a code scent. We will use a consequence builder to make our code a lot clearer.

The very first thing we wish to do is take a block with a listing of gamers (just like what we noticed in SwiftUI) and construct an array from it:

That is our first Consequence Builder!

A Consequence Builder is only a struct marked with @resultBuilder on prime.

The essential methodology we have to add for all Consequence Builders is buildBlock, which takes variadic objects and returns an array. That’s it!

To create a brand new consequence builder, we will simply create a brand new variable prefixed with @TeamBuilder:

Cool, ha?

We eliminated brackets and commas, and our code seems very similar to SwiftUI and HTML!

The following tip isn’t associated to Consequence Builder, but when we take care of a easy code right here, why not discuss it?

We will enhance our code readability utilizing modifiers.

If you happen to wrote SwiftUI code earlier than, you in all probability know what modifiers are.

Now, a modifier isn’t a “characteristic” however slightly a easy design sample that may assist your code turns into way more readable when you have got many properties.

With modifiers, you possibly can chain properties collectively no matter their order and separate them from one another.

We try this by duplicate the struct, set the brand new worth and return an up to date copy:

Offering a listing of gamers is somewhat bit boring.

We would like our DSL to be way more refined. To do this, let’s attempt to implement some logic:

Look easy, ha?

Not so quick. Making an attempt to construct the above code leads to error (however hey, at the least the consequence builder “outcomes” one thing):

Closure containing management move assertion can’t be used with consequence builder ‘TeamBuilder’”

The reason being that the static operate buildBlock expects to obtain a variadic checklist of objects. If-then-else isn’t a part of its expectation.

So as to add help for If-then-else, we have to implement three extra strategies –

buildOptional and buildEither (in two variations).

One necessary rule it’s worthwhile to keep in mind about resultBuilder is that if you’d like it to help extra strategies slightly than buildBlock, the part and the consequence have to be the identical sort. One thing like that:

static func buildBlock(_ elements: [Player]…) -> [Player] {

However that can pressure us to create a listing of arrays of Participant as a substitute of only a checklist of Participant.

To help each Participant and [Player] we will use Protocol:

PlayerGroup will be both a single Participant or an array of Participant.

Now let’s see how one can add the extra strategies:

Recompile the code, and it really works!

Discover I’ve modified the buildBlock methodology to work with PlayerGroup as a substitute of Participant.

Upon getting a Consequence Builder, you possibly can implement it as a part of an init methodology:

I’ve added modifiers to the Workforce struct, however that’s optionally available and solely right here to make the code extra SwiftUI type.

With Consequence Builder, you are able to do wonderful issues, restricted by your creativeness and abilities.

Listed here are just a few concepts:

– Render Screens in UIKit

– Construct HTTP requests.

– Draw shapes with Core Graphics.

– Create Knowledge Buildings.

– Generate attributed strings.

– Create key-frame animations.

And all of that in your personal readable and simple “language”.

For instance, the next code is a Path built-in Consequence Builder:

Are you able to consider extra examples?

More Posts