Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Created November 19, 2015 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/258eac7a531b13b8182e to your computer and use it in GitHub Desktop.
Save krzyzanowskim/258eac7a531b13b8182e to your computer and use it in GitHub Desktop.
import Cocoa
enum Nutrients: String {
case fat, calcium
}
protocol NutrientsType {
var calcium: Int { get }
var fat: Int { get }
}
struct Meal: NutrientsType {
var calcium: Int
var fat: Int
}
extension NutrientsType {
static func total(meals: [Self], nutrient: Nutrients) -> Int {
return meals.reduce(0) { (sum, meal) -> Int in
for child in Mirror(reflecting: meal).children where child.label == nutrient.rawValue {
let valueMirror = Mirror(reflecting: child.value)
if valueMirror.subjectType == Optional<Int>.self {
return sum + ((valueMirror.children.first?.1 as? Int) ?? 0)
} else {
return sum + (child.value as! Int)
}
}
return sum
}
}
}
extension Array where Element: NutrientsType {
func total(nutrition: Nutrients) -> Int {
return Element.total(self, nutrient: nutrition)
}
}
let meal1 = Meal(calcium: 3, fat: 30)
let meal2 = Meal(calcium: 13, fat: 20)
Meal.total([meal1, meal2], nutrient: .fat)
[meal1, meal2].total(.fat)
[meal1, meal2].total(.calcium)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment