comment 0

#49 The Builder Pattern

In issue #41 in which we have built an app that uses a photo camera to capture one’s loayalty cards we used a pattern that we named Builder to configure properties of objects. How does the code look like when we use Builder pattern?

We simply initialize an object we want to configure and call the with(:) function on the newly initilized object. The with(:) function takes only one parameter – a closure in which one has possibility to set up properties of the object. How does it look like in the code?

We created a protocol named Builder and in extension we created a default implementation of the with(:) function:

The with(:) function is very simple – it takes configure closure as a parameter. The closure is immediately called with self which allows "configuring" self – e.g. setting properties on it. We also conformed NSObject to this protocol so that every subclass can use .with{} syntax:

If we create a class that doesn’t inherit from NSObject we need to conform to the protocol manually:

We can check if our pattern works by using assertions from XCTest framework:

There is one problem with the presented approach. It doesn’t work for value types (i.e. struct).

A struct given as a parameter to the configure closure is immutable by default. In order to make it mutable we need to use inout keyword and pass a reference to a type we want to configure. We want the syntax to work with class and struct types and we want to be able to assign returned type to a variable (as previously). So let’s create a BetterBuilder!

Our BetterBuilder now works for structs!

And it still works for classes!


Leave a Reply