Ryan Hampton Ryan Hampton - 1 year ago 79
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download