swift - 访问字典键/值时出现模棱两可的错误
问题描述
我正在使用 Swift 4、AlamoFire 和 SwiftyJSON 来使用 API 中的一些数据。
我为 AlamoFire 创建了一个通用包装器
我的 API 类
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))
}
}
}
这很好用。它获取数据并将其返回给我。
我正在尝试在使用submitSearch()
此 json 片段下方的函数时得到的表格视图中显示这些结果
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]
还有许多其他人。
我究竟做错了什么?如何访问数组中的字典?
解决方案
问题是它tableData[indexPath.row]
不是字典,所以你不能as
用来转换参考。您需要使用tableData[indexPath.row].dictionaryValue
,它返回一个[String : AnyObject]?
.
我认为您的代码将如下所示:
let person = tableData[indexPath.row].dictionaryValue
let name = person?["Name"]
推荐阅读
- awk - gnuplot 格式时间戳日期和时间 AM PM 与 awk
- javascript - 将 HTML 输入限制为特定的字符类型
- reactjs - 部署后反应路由器在云环境中不起作用
- c++ - 每次编译和运行时,我都会收到此错误:main.cpp:15:29: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
- mysql - MySQL:按最新的日期时间列排序?
- spring-boot - requestBody 不可用
- css - 更改材质 UI 步进器中错误图标的颜色
- javascript - 将变量传递给 eventListener 中的箭头函数
- php - iCal 与 Booking com、Airbnb、TripAdvisor 同步
- python - 具有多索引列的 Pandas 数据框 - 将列从 0 级移动到 1 级(不交换或重新排序)