【问题标题】:Index out of range error in swift 3.0swift 3.0中的索引超出范围错误
【发布时间】:2018-04-04 06:59:07
【问题描述】:
func loadMoreData(lBound: Int, uBound: Int){

    for i in lBound...uBound{
        tempArray.append(arrayDealPage[i])
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
        self.dealsTable.reloadData()
    })
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if arrayDealPage.count != tempArray.count
    {
        let lastItem = tempArray.count - 1
        if indexPath.row == lastItem{

            loadMoreData(lBound: tempArray.count, uBound:(tempArray.count-1)+20)

        }
    }
}

我从图像数组中获取 195 个数据,我想一次只显示 20 个,然后滚动添加另外 20 个。上面的代码工作正常,但是当我达到大约 181 或 182 个单元格时,它会崩溃索引超出范围错误.195数组计数将来可能会增加如何解决索引超出范围错误。有人可以帮助我提前感谢。

【问题讨论】:

    标签: arrays uitableview swift3


    【解决方案1】:

    您不检查 uBound 索引是否在 arrayDealPage 数组边界之外。 试试这个:

    func loadMoreData(lBound: Int, uBound: Int){
        // checkeduBound variable never go outside the array bounds
        var checkeduBound = uBound
        if uBound >= arrayDealPage.count {
            checkeduBound = arrayDealPage.count-1
        }
    
        //edited
        if lBound > checkeduBound { return }
    
        //use new checkeduBound here
        for i in lBound...checkeduBound{
            tempArray.append(arrayDealPage[i])
        }
    
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
            self.dealsTable.reloadData()
        })
    }
    

    【讨论】:

    • 兄弟此代码是否适用于我的 195 个数据或将适用于更多数据也意味着条件@Jaba Odishelashvili
    • 是的,它应该适用于任何情况,甚至数组变大。是不是又崩溃了?
    • 一个崩溃发生了致命错误:不能用上界形成范围
    • for i in lBound...checkeduBound{ tempArray.append(arrayDealPage[i]) } 如果调用 api 数组计数为空,应用程序将在此处崩溃
    • 帮我@Jaba Odishelashvili
    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多