swift - TableView中如何使用swiftyJson获取arrayvalue?
问题描述
我使用 swiftyJson 解析数据,但不知道如何解析数组。这是代码。
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var json:JSON = JSON.null
var urlSession = URLSession(configuration: .default)
@IBOutlet weak var myTableView: UITableView!
var pokamon = [[String:AnyObject]]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokamon.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
var dict = pokamon[indexPath.row]
cell.nameLbl.text = dict["name"] as? String
cell.typesLbl.text = dict["types"]?[0] as? String
cell.hpLbl.text = dict["hp"] as? String
cell.subtypeLbl.text = dict["subtype"] as? String
if let image = URL(string: dict["imageUrl"] as! String){
let task = urlSession.downloadTask(with: image) { (url, repsponse, error) in
if error != nil{
print("sorry")
return
}
if let okURL = url{
do{
let downloadImage = UIImage(data: try Data(contentsOf: okURL))
DispatchQueue.main.async {
cell.myImage.image = downloadImage
}
}catch{
print("error")
}
}
}
task.resume()
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 224
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
Alamofire.request("https://api.pokemontcg.io/v1/cards").responseJSON(completionHandler: { response in
if response.result.isSuccess {
let json:JSON = try! JSON(data: response.data!)
let swiftyJsonVar = JSON(response.result.value!)
if let resData = swiftyJsonVar["cards"].arrayObject{
self.pokamon = resData as! [[String:AnyObject]]
}
if self.pokamon.count > 0{
self.myTableView.reloadData()
}
} else {
print("error: \(response.error)")
}
})
}
}
从 tableView 中的 cellForRowAt 显示,下面的代码显示“不明确使用 'subscript'”,不知道如何解决。其余的像“name”、“hp”和“subtype”都没有问题!
cell.typesLbl.text = dict["types"]?[0] as? String
谁能帮我解决这个错误?谢谢!
解决方案
编译器必须知道任何下标对象的类型。告诉编译器您需要一个字符串数组。
cell.typesLbl.text = (dict["types"] as? [String])?.first
在 Swift 3+ 中,所有 JSON 值Any
都不是 AnyObject 所以声明数组
var pokamon = [[String:Any]]()
推荐阅读
- c# - UTF8 中的 WebClient DownloadString 不返回法语字符
- amazon-web-services - 如何使用 Node.js 从 AWS Lambda 中的 /tmp 文件夹将 WAV 文件上传到 S3
- html - 我怎么把
内容 在最小高度的 div 底部? - javascript - a11y 可作为按钮访问的表单输入
- haskell - 在 Haskell 中建模异构图
- jquery - 使用 Metalclone 克隆部分,将所有新项目放入错误的部分
- sql - 如何在 SQL Server 中对表的列进行哈希处理?
- javascript - 是否可以使用 2 个工厂函数来填充 1 个实例?
- c# - 如何安全地反序列化密钥/数据格式 JSON 响应
- java - 语法错误,插入“{”以完成 EnumBody(在类结束时)