致命错误:在Swift中访问10个元素的数组时,数组索引超出范围

问题描述 投票:1回答:2

我正在使用SwiftyJson和Alamofire访问JSON。我把我的产品名称放到一个数组中,但是当我试图访问它的UITableView时:product_name[0],我从标题中收到错误(索引超出范围)。这是代码:

let total_products:Int = json["products"].count;
var i:Int = 0;

for (i=0;i<total_products;i++)
{
    product_name.append(json["products"][i])
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath     indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel!.text = product_name[indexPath.row];

    return cell
}
ios arrays swift uitableview
2个回答
0
投票

要避免超出范围错误,请确保numberOfRowsInSection返回的UITableViewDataSource是数组中元素的数量。

return product_name.count

0
投票

我做到了!

我在self.tableView.reloadData();循环中添加了for,现在我的TableView已经填充了。

感谢你们 !

© www.soinside.com 2019 - 2024. All rights reserved.