-
-
Save krzyzanowskim/258eac7a531b13b8182e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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