Aniket Patil Aniket Patil - 3 months ago 14
Swift Question

How to get all keys and values into separate String arrays from NSDictionary in Swift?

let urlAsString = "https://drive.google.com/uc?export=download&id=0B2bvUUCDODywWTV2Q2IwVjFaLW8"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()

let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
do {
if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {

print(jsonResult)

}
} catch let error as NSError {
print(error)
}


})
jsonQuery.resume()


Okay so here i am receiving data from online json then storing it as NSDictionary in jsonresult . I need to get all keys and values as into two separate arrays ?

Basically i want this

jsonresult.allkeys --> String array

jsonresult.allvalues --> String array

Answer

You can use:

let keys = jsonResult.flatMap(){ $0.0 as? String }  
let values = jsonResult.flatMap(){ $0.1 }  
Comments