简体   繁体   中英

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

You can use:

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

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
}

For anyone trying it with newer version Swift please use compactMap()instead of flatMap()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM