如何从Swift中的NSDictionary中将所有键和值获取到单独的String数组中


    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()

好的,这里我从在线json接收数据,然后将其存储为jsonresult中的NSDictionary。我需要将所有键和值作为两个单独的数组?

基本上我想要这个

jsonresult.allkeys-->字符串数组
jsonresult.allvalues-->字符串数组

您可以使用:

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

这很简单,因为您使用的是jsonResult作为NSDictionary

let dict: NSDictionary = ["Key1" : "Value1", "Key2" : "Value2"]
let keys = dict.allKeys
let values = dict.allValues

在你的情况下

let keys:[String] = dict.allKeys as! [String]
var values:[String]
if let valuesSting = dict.allValues as? [String] {
    values = valuesSting
}

对于任何尝试使用新版本Swift的人,请使用compactMap((而不是flatMap((

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

最新更新