【问题标题】:How to get all keys and values into separate String arrays from NSDictionary in Swift?如何将所有键和值从 Swift 中的 NSDictionary 获取到单独的字符串数组中?
【发布时间】:2016-08-07 07:27:19
【问题描述】:
    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 接收数据,然后将其作为 NSDictionary 存储在 jsonresult 中。我需要将所有键和值放入两个单独的数组中?

基本上我想要这个

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

【问题讨论】:

    标签: ios arrays json swift


    【解决方案1】:

    你可以使用:

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

    【讨论】:

    • “NSData”类型的值没有成员“flatMap”
    • @AniketPatil,更正了,应该是jsonResult 而不是jsonData
    【解决方案2】:

    这很简单,因为您使用 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
    }
    

    【讨论】:

    • (数组) clientSuggestions=jsonResult.allKeys;我收到此错误,因为 无法将类型“[AnyObject]”的值分配给类型“[String]”
    • clientSuggestions 是 [String] 并且 allKeys 是 [AnyObject]
    【解决方案3】:

    如果有人尝试使用较新版本的 Swift,请使用 compactMap() 而不是 flatMap()

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

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 2017-12-20
      • 2021-04-24
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多