The Builder pattern in Swift

Let’s build things

In recent days I started to use the “Builder Pattern” in my Objective-C projects, especially when creating multiple different instances of classes. I often use this when I am dealing with different color/font themes for my iOS apps. Before your read further I must admit that I yet have to fully read the Swift book from Apple, and I havent seen all their WWDC 2014 sessions. There are probably more elegant ways of solving the same problems using Swift, so this blog entry might not be the best practise of the pattern itself.

So back to Swift and the Builder Pattern. The best way to learn a new language is to write code so let continue with doing that.

First lets create a Theme Protocol that we later can conform to.

protocol ThemeProtocol {
var backgroundColor:UIColor? { get }
var textColor:UIColor? { get }

ThemeProtocol is very simple, it only has two simple properties, both for colors. They are also both declared as optional because they will not be set until we call our closure.

Next we create our Theme class that will build our themes.

class Theme : ThemeProtocol {
var backgroundColor:UIColor?
var textColor:UIColor?
typealias buildThemeClosure = (Theme) -> Void
    init(build:buildThemeClosure) {

I added a init method that will take a Closure/Block that returns nothing, but takes a Theme as a paramter.

Now we are ready to create and initalize themes using our Theme class.

let darkTheme = Theme(build: {
$0.backgroundColor = UIColor.blackColor()
$0.textColor = UIColor.whiteColor()
let lightTheme = Theme(build: {
$0.backgroundColor = UIColor.whiteColor()
$0.textColor = UIColor.blackColor()

There you have it, a very simple builder pattern in Swift.

For simple classes like this, its probably easier to pass the two properties by params to the Theme initializer, or just set them by accessing the property. But if ThemeProtocol would have a few more properties, this would be my preferred way of creating objects.


Please follow me on Twitter: