gpt4 book ai didi

swift - 访问字典键/值时出现模棱两可的错误

转载 作者:行者123 更新时间:2023-11-28 05:51:55 25 4
gpt4 key购买 nike

我正在使用 Swift 4、AlamoFire 和 SwiftyJSON 来使用来自 API 的一些数据。

我为 AlamoFire 创建了一个通用包装器

MyApiClass

  func post(_ product: String = "", noun: String, verb: String, onCompletionHandler: @escaping (Bool, JSON) -> Void) {
Alamofire.request(url, method: .post, parameters: package, encoding: JSONEncoding.default).responseJSON {
response in

let json : JSON = JSON(response.result.value!)
if let r = json["APICall"]["Data"].dictionaryObject {
onCompletionHandler(true, JSON(r))
}
}
}

这很好用。它获取数据并将其返回给我。

我试图在一个 TableView 中显示这些结果,当我在这个 json 代码段下方使用 submitSearch() 函数时得到的结果

JSON 值

{
"Results": {
"People": [
{
"Name": "John Smith",
"Address": "123 Main Str",
"Age": "47"
},
{
"Name": "Jane Smith",
"Address": "1234 E Main Str",
"Age": "27"
}
]
}
}

为 UITableView 加载数据的搜索函数

   func submitSearch() {

MyApiClass().post(noun: "Get", verb: "People", data: data) { (isSuccessful, result) in

//This line loads all the array result from the People object in the above json
self.tableData = result["Results"]["People"].arrayValue

self.title? = "\(self.tableData.count) Found"
self.tableView.reloadData()
}

}

我的问题是在填充表格单元格时。在尝试访问词典时,我不断收到 “对成员‘下标’的模糊引用” 和其他错误。

var tableData : Array<Any> = []

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

let person = tableData[indexPath.row] as! Dictionary
let name = person["Name"]

cell.textLabel?.text = "Name: \(String(describing: name))"

return cell
}

tableView(_:cellForRowAt:) 期间,我创建了一个 person 对象,并试图获取存储在 tableData 中 indexPath.row 的字典

我试过了

 let person = tableData[indexPath.row] as! Dictionary
let person = tableData[indexPath.row] as? [String:String]
let person : Dictionary = tableData[indexPath.row]

还有很多其他的。

我做错了什么?如何访问数组中的字典?

最佳答案

问题是 tableData[indexPath.row] 不是字典,因此您不能使用 as 来转换引用。您需要使用 tableData[indexPath.row].dictionaryValue,它返回一个 [String : AnyObject]?

我认为您的代码将如下所示:

let person = tableData[indexPath.row].dictionaryValue
let name = person?["Name"]

关于swift - 访问字典键/值时出现模棱两可的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52653547/

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