swift - 无法将类型 '__NSDictionaryI' 的值转换为 'NSArray'

标签 swift

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  @IBOutlet weak var TableViewOutlet: UITableView!

 let URL_GET_DATA = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=17.500010,78.461527&radius=1000&types=atm&key=AIzaSyA4G66cD6FTzU1UnLO2UHL2rpehzDNa2v4"

 var icons = [Icon]()


override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(URL_GET_DATA).responseJSON { response in


        if let json = response.result.value {

            let iconArray : NSArray  = json as! NSArray

            for i in 0..<iconArray.count{

                self.icons.append(Icon(
                    name: (iconArray[i] as AnyObject).value(forKey: "name") as! String,
                    imageUrl: (iconArray[i] as AnyObject).value(forKey: "imageUrl") as! String
                ))
            }

            self.TableViewOutlet.reloadData()
        }

    }

    self.TableViewOutlet.reloadData()
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "one", for: indexPath)as? TableViewCell

    let icon: Icon
    icon = icons[indexPath.row]

    cell?.nameOutlet.text = icon.name

    Alamofire.request(icon.imageUrl).responseImage { response in
        debugPrint(response)

        if let image = response.result.value {
            cell?.ImageOutlet.image = image
        }
    }
    return cell!
}

}

我收到这样的错误

Could not cast value of type '__NSDictionaryI' (0x10a439508) to 'NSArray' (0x10a439008). 2018-09-27 17:42:43.020278+0530 TableViewJSON[14887:1123768] Could not cast value of type '__NSDictionaryI' (0x10a439508) to 'NSArray' (0x10a439008).

在第 30 行我收到一条错误消息

Thread1: signal SIGABRT

最佳答案

错误非常明显:json是一个字典([String:Any]),而不是一个数组。根本不要在 Swift 中使用 NSArray – 以及可怕的 as AnyObject).value(forKey: – !

并且始终有条件地绑定(bind)值以避免崩溃

...
   if let json = response.result.value as? [String:Any], // <- Swift Dictionary
      let results = json["results"] as? [[String:Any]]  { // <- Swift Array

      for result in results {
          print(result["name"] as! String)
      }

JSON 中根本没有关键的 imageURL

关于swift - 无法将类型 '__NSDictionaryI' 的值转换为 'NSArray',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536876/

相关文章:

xcode - 每次我尝试在我的登录页面上登录用户时,我都会收到无效的登录参数

ios - 如何在 Firebase 中检索自动生成的 ID/ key ?

swift - 如何根据图像调整 UIImaveView 的大小?

ios - 在 swift 中解析 Json 后获取空数据

ios - 无法将类型 'TableViewController' 的值转换为 'NSString'

ios - 使用滑动手势在标签栏之间导航

swift - 在 Swift 中转换 followPath(_ :asOffset:orientToPath:speed:) to iOS 7. 1 兼容版本

ios - 如何在 Swift 协议(protocol)中声明可选方法?

swift - 通过更改 uv 坐标在 Metal 中出现意外性能

php - 文件上传应用程序从 PHP 文件返回内部服务器错误