首页 > 解决方案 > 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

谁能帮我解决这个错误?谢谢!

标签: swift

解决方案


编译器必须知道任何下标对象的类型。告诉编译器您需要一个字符串数组。

cell.typesLbl.text = (dict["types"] as? [String])?.first

在 Swift 3+ 中,所有 JSON 值Any都不是 AnyObject 所以声明数组

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

推荐阅读