Menu
Coddy logo textTech

Builder Pattern

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 48 of 57.

The builder pattern assembles a complex object step by step. Each step sets one part and returns the builder, so the steps can be chained, and a final build() creates the finished object:

struct Request {
    let url: String
    let method: String
    let headers: [String: String]
}

struct RequestBuilder {
    private var url = ""
    private var method = "GET"
    private var headers: [String: String] = [:]

    func url(_ u: String) -> RequestBuilder { var b = self; b.url = u; return b }
    func method(_ m: String) -> RequestBuilder { var b = self; b.method = m; return b }
    func header(_ k: String, _ v: String) -> RequestBuilder { var b = self; b.headers[k] = v; return b }
    func build() -> Request { Request(url: url, method: method, headers: headers) }
}

let req = RequestBuilder().url("/users").method("POST").header("Auth", "token").build()
print("\(req.method) \(req.url) \(req.headers.count) header")

Output:

POST /users 1 header

The builder can check the whole configuration before creating the object, so an invalid object is never built. Here build() throws when a required part is missing:

enum BuildError: Error { case missingURL }

struct Request { let url: String; let method: String }

struct RequestBuilder {
    private var url: String?
    private var method = "GET"
    func url(_ u: String) -> RequestBuilder { var b = self; b.url = u; return b }
    func method(_ m: String) -> RequestBuilder { var b = self; b.method = m; return b }
    func build() throws -> Request {
        guard let url else { throw BuildError.missingURL }
        return Request(url: url, method: method)
    }
}

do {
    _ = try RequestBuilder().method("PUT").build()
} catch {
    print("cannot build: \(error)")
}

Output:

cannot build: missingURL

Each step copies the struct and changes the copy, so a builder that is partly configured can be reused as a template for several objects:

struct PizzaBuilder {
    private var size = "medium"
    private var toppings: [String] = []
    func size(_ s: String) -> PizzaBuilder { var b = self; b.size = s; return b }
    func add(_ t: String) -> PizzaBuilder { var b = self; b.toppings.append(t); return b }
    func build() -> String { "\(size) pizza with " + (toppings.isEmpty ? "nothing" : toppings.joined(separator: ", ")) }
}

let base = PizzaBuilder().size("large").add("cheese")
print(base.add("ham").build())
print(base.add("olives").build())

Output:

large pizza with cheese, ham
large pizza with cheese, olives

Swift's default parameter values already cover simple cases (Request(url: "/", method: "GET")). A builder pays off when an object has many optional parts, parts that depend on each other, or rules to check before it can exist.

// simple: default arguments are enough
struct Point { var x = 0, y = 0 }
// complex: many optional parts and validation -> builder
let report = ReportBuilder().title("Q3").add(section: s1).add(section: s2).footer("draft").build()
challenge icon

Challenge

Easy

Write a builder for email messages. EmailBuilder has chainable steps to(_:) (can be called several times, adding recipients), subject(_:), body(_:) and urgent(). build() returns an Email or throws EmailError.noRecipients or EmailError.noSubject. An urgent email gets [URGENT] in front of its subject.

The supplied code reads commands per email separated by --- lines (to ada@x.io, subject Hello, body text, urgent, then send) and prints To: ada@x.io, bo@x.io | [URGENT] Hello | text, error: no recipients or error: no subject.

Your code goes in Email.swift, EmailError.swift and EmailBuilder.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
var builder = EmailBuilder()
for line in input {
    let p = line.split(separator: " ", maxSplits: 1).map(String.init)
    switch p[0] {
    case "to": builder = builder.to(p[1])
    case "subject": builder = builder.subject(p[1])
    case "body": builder = builder.body(p[1])
    case "urgent": builder = builder.urgent()
    case "send":
        do {
            let e = try builder.build()
            print("To: \(e.recipients.joined(separator: ", ")) | \(e.subject) | \(e.body)")
        } catch EmailError.noRecipients {
            print("error: no recipients")
        } catch {
            print("error: no subject")
        }
    default: builder = EmailBuilder()
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground