首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Swift 5:从tableView numberOfRowsInSection返回数组计数时索引超出范围

Swift 5:从tableView numberOfRowsInSection返回数组计数时索引超出范围
EN

Stack Overflow用户
提问于 2019-06-09 23:17:30
回答 1查看 127关注 0票数 0

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

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

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

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

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
    }


}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-10 00:21:10

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

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sample.first?.articles.count ?? 0
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56515799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档