首页 > 解决方案 > 访问字典键/值时出现模棱两可的错误

问题描述

我正在使用 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]

还有许多其他人。

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

标签: swiftuitableviewdictionaryswift4

解决方案


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

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

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

推荐阅读