A lot of what you're attempting to do can be accomplished using Swift's map
, sorted
, filtered
, and reduce
functions.
struct CalorieLog {
var date: Date
var calories: Int
}
var logs: [CalorieLog] = []
// I changed your method to pass in calculatedCalories, we can make that random just for learning purposes. See below
func logCalories(calculatedCalories: Int) {
let currentDate: Date = Date()
logs.append(CalorieLog(date: currentDate, calories: calculatedCalories))
}
// This is a method that will calculate dummy calorie data n times, and append it to your logs array
func addDummyCalorieData(n: Int, maxRandomCalorie: Int) {
for _ in 1...n {
let random = Int(arc4random_uniform(UInt32(maxRandomCalorie)))
logCalories(calculatedCalories: random)
}
}
// Calculate 100 random CalorieLog's with a max calorie value of 1000 calories
addDummyCalorieData(n: 100, maxRandomCalorie: 1000)
// Print the unsorted CalorieLogs
print("Unsorted Calorie Data: \(logs)")
// Sort the logs from low to high based on the individual calories value.
let sortedLowToHigh = logs.sorted { $0.calories < $1.calories }
// Print to console window
print("Sorted Low to High: \(sortedLowToHigh)")
// Sort the CalorieLogs from high to low
let sortedHighToLow = logs.sorted { $1.calories < $0.calories }
// Print to console window
print("Sorted High to Low: \(sortedHighToLow)")
// Sum
// This will reduce the CaloreLog's based on their calorie values, represented as a sum
let sumOfCalories = logs.map { $0.calories }.reduce(0, +)
// Print the sum
print("Sum: \(sumOfCalories)")
If you wanted to map your CalorieLogs as an array of dictionaries you could do something like this:
let arrayOfDictionaries = logs.map { [$0.date : $0.calories] }
However that's kind of inefficient. Why would you want an array of dictionaries? If you just wanted to track the calories consumed/burned for a specific date, you could just make one dictionary where the date is your key, and an array of Int
is the value which represents all the calories for that day. You probably would only need one dictionary, i.e.
var dictionary = [Date : [Int]]()
Then you could find all the calories for a date by saying dictionary[Date()]
. Although keep in mind that you would have to have the exact date and time. You may want to change the key of your dictionary to be something like a String
that just represents a date like 2/19/2017
, something that could be compared easier. That will have to be taken into account when you design your model.