The Builder pattern in Swift

Let’s build things

Mikael Konradsson
Jun 24, 2014 · 2 min read

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) {
build(self)
}
}

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.

Enjoy!

Please follow me on Twitter: https://twitter.com/konrad1977

Swift Programming

The Swift Programming Language

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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