类型“Any”没有下标成员indexPath

时间:2016-11-22 16:16:02

标签: swift3 xcode8

我正在尝试从mysql数据库获取信息,我有以下代码。我曾尝试使用其他页面上的编辑,但我是编程新手,无法弄清楚我做错了什么。

    func get(){
    let url = URL(string: "http://192.168.157.134/Getdepartment.php")
    let data = try? Data(contentsOf: url!)
    values = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
    tableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return values.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SpecialCell
    let maindata = values[indexPath.row]
    cell.username.text = maindata["Username"] as? String
    cell.password.text = maindata["Password"] as? String
    cell.num.text = maindata["FavoriteNumber"] as? String
    cell.info.text = maindata["Info"] as? String
    return cell;

}

1 个答案:

答案 0 :(得分:1)

如前所述,Foundation NSArray通常不提供类型信息,因此它根本无法帮助Swift编译器。

在Swift 3中,编译器必须知道所有下标对象的类型,否则会出错。

要解决此问题,首先要将您的数据源数组声明为包含Swift Array的Swift Dictionary。这使编译器 - 最终你 - 很高兴。

var values = [[String:Any]]()

如果所有字典值都是字符串,您甚至可以将values声明为[[String:String]]

其次将反序列化行转换为相同的类型:

values = try! JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]

PS:mutableContainers在Swift中没用,传递空options

旁注:

即使在本地网络中,也不要通过Data(contentsOf:

同步加载来自远程URL的数据
相关问题