ios - swift 5 : index out of range when returning the array count from tableView numberOfRowsInSection

标签 ios swift uitableview uikit

我几乎解决了这个问题。这是唯一需要解决的问题。

这就是我要解析的内容: https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=API_KEY

sample[0].articles.count 出现索引超出范围的错误

我正在尝试用我解析的数据填充标签。我试过了,它只返回 1 个单元格。

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

ViewController.swift

import UIKit

struct News: Decodable {

    let articles: [Article]

    struct Article: Decodable {
        let title: String?
        let urlToImage: String?
        let description: String?
    }
}
class ViewController: UIViewController {

    @IBOutlet weak var table: UITableView!

    var sample = [News]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        getJson()

        table.delegate = self
        table.dataSource = self

    }

    func getJson() {
        let urlString = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=e07d26ea273d41e2af174b026aea27b5"

        guard let url = URL(string: urlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else { return }

            do {
                self.sample = [try JSONDecoder().decode(News.self, from: data)]
                print(self.sample[0].articles.count)
                for dict in self.sample {
                    for sam in dict.articles {
                        print(sam.title!)
                    }
                }

                DispatchQueue.main.async {
                    //reload tableView data
                    self.table.reloadData()
                }

            } catch let jsonErr {
                print("json error: ", jsonErr)
            }
        }.resume()
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sample[0].articles.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(100)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        let json = sample[0].articles[indexPath.row]
        cell.name.text = "\(json.title!)"
        cell.link.text = "\(json.description!)"
        cell.imageUrl.text = "\(json.urlToImage!)"
        return cell
    }


}

最佳答案

您正在异步设置 sampletableView(_ tableView: UITableView, numberOfRowsInSection section: Int)sample 包含任何内容之前被调用。 以下更改将防止崩溃。

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sample.first?.articles.count ?? 0
    }

关于ios - swift 5 : index out of range when returning the array count from tableView numberOfRowsInSection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515799/

相关文章:

ios - 如何在 iOS 中以编程方式创建范围 slider ?

ios - 快速:调用 willDisplay

ios - "cannot increment endIndex"- 由于 UITextView 中的表情符号字符而出错

ios - UITableview在每行出现之前无法平滑滚动?

ios - UITableView 的 iCarousel 性能问题(iPad 主从 UI)

ios - UITableViewCell 中 UITextField View 的边框颜色

ios - 将 UILabel 添加到 UITableViewCell 时遇到问题

iphone - 我无法在 iphone sdk 中使用 Amazon Web Services s3 uploader

objective-c - 查找当前键盘的语言

swift - ANTLR 中 WS 背后的魔力是什么?