Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 665
Heisenberg Avatar asked Aug 07 '16 07:08

Heisenberg


2 Answers

You can use:

let keys = jsonResult.flatMap(){ $0.0 as? String }  
let values = jsonResult.flatMap(){ $0.1 }  
like image 51
Khundragpan Avatar answered Nov 05 '22 21:11

Khundragpan


It is quite simple because you are using jsonResult as NSDictionary.

let dict: NSDictionary = ["Key1" : "Value1", "Key2" : "Value2"]

let keys = dict.allKeys
let values = dict.allValues

In you're case

let keys:[String] = dict.allKeys as! [String]

var values:[String]

if let valuesSting = dict.allValues as? [String] {
    values = valuesSting
}
like image 43
Oleg Gordiichuk Avatar answered Nov 05 '22 22:11

Oleg Gordiichuk