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

标签 swift uitableview dictionary swift4

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

相关文章:

ios - Xcode控制台调试输出

python - 将字符串连接到列表字典中的键和值

python - 使用 python 创建分层数据。基于结果列表

swift - 在选择器 View 中选择项目后需要显示 TextView

ios - 无法隐藏导航工具栏

iphone - 呈现 UIViewController 作为 tableViewCell 的详细 View 后错误解雇

python - 获取字典的父子关系

ios - swift 4 中的旋转轮盘赌

ios - 如何更改 Swift Xcode 6 中的按钮文本?

iphone - 如何在不使用重新加载的情况下隐藏 UITableViewCell 中的重新排序控件?