【问题标题】:Ambiguous error when accessing Dictionary key/values访问字典键/值时出现模棱两可的错误
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    “对成员'下标'的模糊引用”

    出现此错误是因为您没有为字典传递任何类型。使用as! Dictionary&lt;String, Any&gt; 而不是as! Dictionary

    您可以将tableData 定义为:

        var tableData: Array<Dictionary<String, Any>> = []
    

    或者更确切地说,使用现有的 tableData 声明更新您的代码:

        let person = tableData[0] as? Dictionary<String, Any>
        let name = (person?["name"] as? String) ?? ""
        cell.textLabel?.text = "Name: \(name)"
    

    或者更好的错误处理,

        if let person = tableData[0] as? Dictionary<String, Any>, let name = person["name"] as? String {
            cell.textLabel?.text = "Name: \(name)"
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 2013-01-18
      • 2014-08-12
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多