swift - Converting String into NSDate in array of dictionaries -
i doing requests api returns me following sample :
[{ id = 1004; "planning_id" = 7; "started_on" = "2015-05-14";}, { id = 1380; "planning_id" = 8; "started_on" = "2015-05-16";}, { id = 1382; "planning_id" = 8; "started_on" = "2015-05-18"; }]
as can see, date value returned string considered anyobject now...
i trying change dictionaries of array can use started_on value nsdate
here code :
in 1..<myarray.count { let datestring = shiftsarray[i-1].objectforkey("started_on") as! string //format date var dateformatter = nsdateformatter() dateformatter.dateformat = "yyyy-mm-dd" var datefromstring = dateformatter.datefromstring(datestring) shiftsarray[i-1].objectforkey("started_on") = datefromstring }
however, cannot run code since have error last line : "cannot assign value of type 'nsdate?' value of type "anyobject?".
the problem don't know how change value type of 'started_on' of dictionnaries.
thank in advance,
i dont know how set things before little snippet in question how did:
var arr:[[string:anyobject]] = [["id":1, "planning_id":2, "started_on":"2015-05-13"], ["id":1, "planning_id":2, "started_on":"2015-05-14"], ["id":1, "planning_id":2, "started_on":"2015-05-10"]] (i, dict) in enumerate(arr) { let datestring = dict["started_on"] as! string let formatter = nsdateformatter() formatter.dateformat = "yyyy-mm-dd" let date = formatter.datefromstring(datestring) arr[i]["started_on"] = date } // mentioned want sort based on date: arr.sort { obj1, obj2 -> bool in let date1 = obj1["started_on"] as! nsdate let date2 = obj2["started_on"] as! nsdate return date1.compare(date2) == nscomparisonresult.orderedascending }
before:
var myarray = [ [ "id" : 1004, "planning_id" : 7, "started_on" : "2015-05-14" ], [ "id" : 1380, "planning_id" : 8, "started_on" : "2015-05-16" ], [ "id" : 1382, "planning_id" : 8, "started_on" : "2015-05-18" ] ]
after:
[{ id = 1004; "planning_id" = 7; "started_on" = "2015-05-14 07:00:00 +0000"; }, { id = 1380; "planning_id" = 8; "started_on" = "2015-05-16 07:00:00 +0000"; }, { id = 1382; "planning_id" = 8; "started_on" = "2015-05-18 07:00:00 +0000"; }]
Comments
Post a Comment