Swift从Dictionary获得价值

时间:2016-07-22 06:15:51

标签: swift

请帮助我从回复中获取值

{
  "BU": {
    "name": "Bulawayo",
    "names": "Bulawayo"
  },
  "HA": {
    "name": "Harare",
    "names": "Harare"
  }
}

我想要关键名称的价值。我的代码在下面

let response = responseObject as! Dictionary<String,AnyObject>
let stateNames = response.values as! Dictionary<String,AnyObject>

遇到此问题:

cannot cast from lazyMapCollection<Dictionary<String,Anyobject>,String> in swift

4 个答案:

答案 0 :(得分:3)

您可以将“BU”的值设为response.valueForKey("BU").valueForKey("name"),它会为您提供“Bulawayo”的值。

答案 1 :(得分:1)

如果你想要所有的名字,那就试试这个

var name = [String]()
let keyArray = responseDic.allKeys as! [String]
for key in keyArray {
    let nameDic = responseDic.valueForKey(key) as! Dictionary<String,AnyObject>
    name.append(nameDic.valueForKey("name") as! String)
}

答案 2 :(得分:0)

您可以执行以下操作来访问值:

if let responseBU = response["BU"] {
   let name = responseBU["name"]
   let names = responseBU["names"] 
}

答案 3 :(得分:-1)

以NSData格式获得响应后,您只需执行以下操作即可获取数据

if let json = try? NSJSONSerialization.JSONObjectWithData(nsdata, options: .MutableContainers) as! NSDictionary {         
    if let some = json["BU"][0]["name"] {
        print(some) // prints -- Bulawayo
    }
}

通过使用subscipt,我们可以获得数据。