我对swift相对较新,我在这里遇到一些问题。 我有一个JSON已经序列化为字典。这就是我得到字典的方式
guard let result = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String:AnyObject] else {
print("Error trying to convert data to JSON")
completionHandler(nil, response, error)
return
}
这是我的词典
{
"count": "68",
"earthquakes": [
{
"src": "us",
"eqid": "b000gbf8",
"timedate": "2013-04-19 03:05:53",
"lat": "46.1817",
"lon": "150.7960",
"magnitude": "7.2",
"depth": "122.30",
"region": "Kuril Islands"
},
{
"src": "us",
"eqid": "b000g7x7",
"timedate": "2013-04-16 10:44:20",
"lat": "28.1069",
"lon": "62.0532",
"magnitude": "7.8",
"depth": "82.00",
"region": "Iran-Pakistan border region"
}
]
}
我希望将这些地震作为一个数组,我可以迭代其中的每个项目。
我尝试为那个
创建一个临时变量let eqs = resultJSON["earthquakes"]
但是,我无法遍历eqs
。我的观点是,我想制作一个来自该词典的数组。
怎么可能?任何帮助,将不胜感激。谢谢。
答案 0 :(得分:3)
密钥earthquakes
包含具有String
个键和值
if let earthquakes = result["earthquakes"] as? [[String:String]] {
for earthquake in earthquakes {
let lat = earthquake["lat"]!
let lon = earthquake["lon"]!
// get other values
print(lat, lon)
}
}