Skip to content

Instantly share code, notes, and snippets.

@ajjames
Created January 19, 2017 20:14
Show Gist options
  • Save ajjames/95e71465019400c33f926b0ca8369ce5 to your computer and use it in GitHub Desktop.
Save ajjames/95e71465019400c33f926b0ca8369ce5 to your computer and use it in GitHub Desktop.
Bakery Example
import Foundation
class Bakery {
func bakeCake() -> Cake? {
let ingredientStorage = IngredientStorage()
if let chocolateFlavor = ingredientStorage.consume(flavor: .chocolate) {
return Cake(flavor: chocolateFlavor)
} else if let vanillaFlavor = ingredientStorage.consume(flavor: .vanilla) {
return Cake(flavor: vanillaFlavor)
}
return nil
}
}
struct Cake: CustomStringConvertible {
let flavor: Flavor
var description: String {
return "\(flavor) cake"
}
}
enum Flavor {
case chocolate
case vanilla
}
class IngredientStorage {
private var pretendStorage: [Flavor] = [.vanilla, .chocolate]
func consume(flavor: Flavor) -> Flavor? {
guard let index = pretendStorage.index(of: flavor) else { return nil }
pretendStorage.remove(at: index)
return flavor
}
}
let bakery = Bakery()
let cake = bakery.bakeCake()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment