gpt4 book ai didi

json - Swift:使用 JSON 文件中具有特定值的数据填充 TableView

转载 作者:行者123 更新时间:2023-11-30 12:57:24 25 4
gpt4 key购买 nike

我知道如何使用基于特定键的 JSON 数据填充 TableView ,但我试图弄清楚如何仅将数据放入 TableView (如果它在键值中具有特定值)一对。

具体来说,我的 JSON 文件包含一个键值对:“位置”:“伊利诺伊州芝加哥”,“大陆”:“美国”

我希望我的表格 View 显示大陆值为“US”的任何条目的位置,并且我不希望它显示与其关联的不同大陆的任何位置。

如果我能得到任何帮助,我将不胜感激。这是我的 parseJSON 文件中的内容,但它目前无法完成我想做的事情。我在 tableview 函数中发现数组索引超出范围

    func parseJSON(){
do{
let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!)

let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

for anItem in jsonResult as! [Dictionary<String, AnyObject>]{

let mifiContinent = anItem["continent"] as! String!
if var mifiContinent = jsonResult["US"]{
let mifiLocation = anItem["location"] as! String
let newLocation = Location(location: mifiLocation)
locationOfMifi.append(newLocation)
}
}
}
catch let error as NSError{
print(error.debugDescription)
}
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath)as? LocationCell{

let location: Location!

location = locationOfMifi[indexPath.row]
cell.configureCell(location)
return cell

} else{
return UITableViewCell()
}

}

最佳答案

只需对过滤进行一些更改

let mifiContinent = anItem["continent"] as! String!
if mifiContinent == "US" {
let mifiLocation = anItem["location"] as! String
let newLocation = Location(location: mifiLocation)
locationOfMifi.append(newLocation)
}

关于json - Swift:使用 JSON 文件中具有特定值的数据填充 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40274761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com