Create a gist now

Instantly share code, notes, and snippets.

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