i new swift. trying make simple rest call , access data returned. testing zippopotam api, returns city information based on zipcode. result rest call , put dictionary:
var jsonresult: nsdictionary = nsjsonserialization.jsonobjectwithdata(data, options:nsjsonreadingoptions.mutablecontainers, error: nil) as! nsdictionary here of data prints out when print json:
{ country = "united states"; "country abbreviation" = us; places = ( { latitude = "40.5541"; longitude = "-111.9539"; "place name" = "south jordan"; state = utah; "state abbreviation" = ut; } ); "post code" = 84095; } first of all, there better way access key value pair than
json["post code"].text! that seems low level information, maybe way in swift.
next, places tuple. when access places, information in parentheses ( info ...). how access state in first tuple? have tried json["places"].0["state"], not correct.
json has 3 basic types - arrays, dictionaries , strings. these mapped nsjsonserialization nsdictionary (which bridged swift dictionary), nsarray (bridged swift array) , nsstring (bridged string).
the simplest way access data returned nsjsonserialization read dictionaries & arrays have.
in case of 'places' array of dictionaries 'state' can say
if let places=json["places"] as? [[string:anyobject]] { if (places.count > 0) { let place=places[0] let state=place["state"] as! string } } the "better" way take json , use create objects appropriate properties. unfortunately unlike xml can use defined schema automatically generate 'parsing' code have yourself