【发布时间】:2018-10-04 19:06:12
【问题描述】:
我正在使用 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))
}
}
}
效果很好。它获取数据并将其返回给我。
我试图在一个表格视图中显示这些结果,当我使用这个 json sn-p 下方的 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()
}
}
我的问题是当我填充表格单元格时。尝试访问字典时,我不断收到"Ambiguous reference to member 'subscript'" 和其他错误。
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 对象并尝试将字典存储在indexPath.row 的tableData 中
我试过了
let person = tableData[indexPath.row] as! Dictionary
let person = tableData[indexPath.row] as? [String:String]
let person : Dictionary = tableData[indexPath.row]
还有很多其他人。
我做错了什么?如何访问数组中的字典?
【问题讨论】:
-
根据我对 Codable 的理解,我必须为 API 调用/结果创建一个新类。这似乎是矫枉过正。如果 json 数据发生变化,我将不得不更改容器类。
-
如果格式发生变化,是的,您必须这样做。但是您的代码需要某种格式无论如何,不是吗?而且一个可以在你背后突然改变 API 的 JSON API 无论如何也不是一个很好的 API,不是吗?这些考虑并没有阻止每个人其他更新到 Decodable,所以很难看出它们如何构成有效的借口。
标签: swift uitableview dictionary swift4