Ryan Hampton Ryan Hampton - 2 months ago 7x
iOS Question

Swift: How to save data to a certain date

I am trying to save data based on the day the data was recorded (e.g. User had 5 apples to eat on the 29/07/2016).

I cant find a way in the documentation to save the data without creating a calendar event. Would the data have to be stored in an array containing both the number of apples eaten and the day the apples were eaten using a struct? and how could the data then be accessed? would it be through the use of global variables?


You could use dictionaries:

You would create a dictionary like this:

var applesPerDay = [NSDate: Int]()

You would set the value for a day like this:

applesPerDay[NSDate()] = 5

You could print all values sorted in chronological order like this:

for key in applesPerDay.keys.sort({$0.compare($1) == .OrderedAscending}) {
    //you may want to format the date
    print("On day \(key) I ate \(applesPerDay[key]!) apples")

If you need to persist the data you could use NSUserDefaults