Instantly share code, notes, and snippets.

@owensd owensd/FancyFeast.swift Secret
Created Feb 2, 2015

Embed
What would you like to do?
Another way of solving the protocols problem from Ash's blog post.
// Playground - noun: a place where people can play
import Cocoa
enum Food {
case Dry(caloriesPerGram: Double)
case Wet(caloriesPerGram: Double, hydrationPerGram: Double)
}
protocol Nutrition {
var calorieCount: Double { get set }
var hydrationLevel: Double { get set }
}
struct Cat: Nutrition {
var calorieCount: Double = 0
var hydrationLevel: Double = 0
}
func eat(var nutrition: Nutrition, food: Food, grams: Double) -> Nutrition {
switch food {
case let .Dry(caloriesPerGram):
nutrition.calorieCount += caloriesPerGram * grams
case let .Wet(caloriesPerGram, hydrationPerGram):
nutrition.calorieCount += caloriesPerGram * grams
nutrition.hydrationLevel += hydrationPerGram * grams
}
return nutrition
}
func eat<T: Nutrition>(nutrition: T, food: Food, grams: Double) -> T {
return eat(nutrition, food, grams) as T
}
let kibble = Food.Dry(caloriesPerGram: 40)
let fancyFeast = Food.Wet(caloriesPerGram: 80, hydrationPerGram: 0.2)
var dave = Cat()
dave = eat(dave, kibble, 30)
dave = eat(dave, fancyFeast, 20)
let cats = [Cat(), Cat(), Cat(), Cat(), Cat(), Cat(), Cat()]
let caloriesEatenByCats = reduce(map(cats) { cat in
eat(cat, kibble, 30) }, 0) { sum, cat in
sum + cat.calorieCount }
caloriesEatenByCats
struct Dog: Nutrition {
var calorieCount: Double = 0
var hydrationLevel: Double = 0
}
let dogs = [Dog(), Dog(), Dog(), Dog()]
let caloriesEatenByDogs = reduce(map(dogs) { dog in
eat(dog, kibble, 30) }, 0) { sum, dog in
sum + dog.calorieCount }
caloriesEatenByDogs
let animals: [Nutrition] = [Dog(), Cat()]
let caloriesEatenByAnimals = reduce(map(animals) { animal in
eat(animal, kibble, 30) }, 0) { sum, animal in
sum + animal.calorieCount }
caloriesEatenByAnimals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment