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