Learn how to implement the builder pattern in Swift to hide the complexity of creating objects with lots of individual properties.


How does the builder pattern work?

The builder pattern can be implemented in multiple ways, but that really doesn't matters if you understand the main goal of the pattern:

The intent of the Builder design pattern is to separate the construction of a complex object from its representation.

So if you have an object with lots of properties, you want to hide the complexity of the initialization process, you could write a builder and construct the object through that. It can be as simple as a build method or an external class that controls the entire construction process. It all depends on the given environment. 🏗

That's enough theory for now, let's see the builder pattern in action using dummy, but real-world examples and the powerful Swift programming language! 💪


Simple emitter builder

I believe that SKEmitterNode is quite a nice example. If you want to create custom emitters and set properties programmatically - usually for a SpriteKit game - an emitter builder class like this could be a reasonable solution. 👾


Simple theme builder

Let's move away from gaming and imagine that you are making a theme engine for your UIKit application which has many custom fonts, colors, etc. a builder could be useful to construct standalone themes. 🔨


"Chained" URL builder

With this approach you can configure your object through various methods and every single one of them will return the same builder object. This way you can chain the configuration and as a last step build the final product. ⛓


The builder pattern with a director

Let's meet the director object. As it seems like this little thing decouples the builder from the exact configuration part. So for instance you can make a game with circles, but later on if you change your mind and you'd like to use squares, that's relatively easy. You just have to create a new builder, and everything else can be the same. 🎬


Block based builders

A more swifty approach can be the use of blocks instead of builder classes to configure objects. Of course we could argue on if this is still a builder pattern or not... 😛

⚠️ Please note that the builder implementation can vary on the specific use case. Sometimes a builder is combined with factories. As far as I can see almost everyone interpreted it in a different way, but I don't think that's a problem. Design patterns are well-made guidelines, but sometimes you have to cross the line.


External sources