Skip to content

Instantly share code, notes, and snippets.

@klaaspieter
Created February 2, 2015 20:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klaaspieter/c05e843896abfa70f5cb to your computer and use it in GitHub Desktop.
Save klaaspieter/c05e843896abfa70f5cb to your computer and use it in GitHub Desktop.
An implementation of the Builder pattern in Swift
import Foundation
enum Cheese : String {
case Mozzarella = "Mozzarella"
case Provolone = "Provolone"
case Pecorino = "Pecorino"
}
class PizzaBuilder {
var size: Int = 0
var cheese: Cheese?
var pepperoni: Bool = false
var mushrooms: Bool = false
}
struct Pizza {
let size: Int
let cheese: Cheese?
let pepperoni: Bool
let mushrooms: Bool
init?(block: (PizzaBuilder -> Void)) {
let builder = PizzaBuilder()
block(builder)
self.init(builder: builder)
}
init?(builder: PizzaBuilder) {
if contains([12, 14, 16], builder.size) {
self.size = builder.size
self.cheese = builder.cheese
self.pepperoni = builder.pepperoni
self.mushrooms = builder.mushrooms
} else {
return nil
}
}
func description() -> String {
var description = "Pizza { size: \(self.size) "
func add(property: Bool, name: String) {
if property {
description += " \(name)"
}
}
if let cheese = self.cheese {
description += " \(cheese.rawValue)"
} else {
description += " No cheese"
}
add(pepperoni, "pepperoni")
add(mushrooms, "mushrooms")
description += " }"
return description
}
}
Pizza() { builder in
builder.size = 12
builder.cheese = .Mozzarella
builder.pepperoni = true
}
Pizza() {
$0.size = 12
$0.mushrooms = true
}
Pizza() {
$0.cheese = .Provolone
$0.pepperoni = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment