我有一些JSON如下
[
{
"id": "1",
"locid": "352260",
"name": "Clifton-on-Teme",
"postcode": "WR6 6EW",
"club": "Warley Wasps",
"lat": "52.257011",
"lon": "-2.443215",
"type": "Soil"
},
{
"id": "2",
"locid": "310141",
"name": "Drayton Manor",
"postcode": "ST18 9AB",
"club": "Warley Wasps",
"lat": "52.745810",
"lon": "-2.102677",
"type": "Soil"
},
(这是其中2组的摘录。)
我有一个代码查找如下
func downloadtrackDetails(completed: @escaping DownLoadComplete) {
Alamofire.request(trackURL).responseJSON { (response) in
if let dict = response.result.value as? [Dictionary<String, Any>] {
if let postcode = dict[0]["postcode"] as? String {
self._postcode = postcode
}
if let trackType = dict[0]["type"] as? String {
self._trackType = trackType
}
}
completed()
}
}
我的主屏幕上有许多项目,每个项目的ID分配为1到8.目前我只能在运行时返回json字典中的第一个条目。我需要做些什么来获取特定id的数据。如果我点击ID为1的第一个图标,它将返回WR6 6EW的邮政编码
答案 0 :(得分:1)
如果id
键没有链接到数组中的位置,则可以简单地遍历dict
并仅在_postcode
属性中指定id
属性匹配您的ID:
for (key, item):[String, String] in dict {
if item["id"] == "YOUR ID" {
if let postcode = item["postcode"] as? String { /* ... */ }
/* ... */
break
}
}
或者您可以过滤dict
以仅保留ID为您正在寻找的ID。
答案 1 :(得分:1)
实际上,您的dict
是一个数组,包含[String:String]
个词典。这摆脱了某种类型的铸造。
您可以使用filter
功能通过id
let id = "2"
if let array = response.result.value as? [Dictionary<String, String>],
let foundItem = array.filter({ $0["id"]! == id }).first {
if let postcode = foundItem["postcode"] {
self._postcode = postcode
}
if let trackType = foundItem["type"] {
self._trackType = trackType
}
}