Swift 3.0出现Index out of range错误,求排查列表加载更多代码问题
Let's break down the problems in your code and fix them step by step:
1. Obvious Syntax Error
First, your tableView(_:willDisplay:forRowAt:) method has incomplete syntax here:
loadMoreData(lBound: tempArray.count, uBound:(tempArray.count-1)+...
This line cuts off mid-calculation, which will prevent your code from compiling at all. We'll fix this along with the array out-of-range issue.
2. Root Cause of "Index out of range"
The core problem is that you're calculating the upper bound for loadMoreData without checking if it exceeds the actual length of arrayDealPage. When you try to access arrayDealPage[i] where i is greater than or equal to arrayDealPage.count, you'll hit the out-of-range error.
Additionally, your current logic doesn't check if there's any remaining data to load before triggering loadMoreData, which could lead to unnecessary (and error-prone) calls.
Fixed Full Code
Here's the corrected implementation with explanations:
// Define a batch size (adjust this to how many items you want to load at once) let loadBatchSize = 10 func loadMoreData(lBound: Int, uBound: Int){ // First, guard against invalid bounds to avoid out-of-range errors guard lBound < arrayDealPage.count else { return // No more data to load } // Calculate the actual upper bound (can't exceed the last index of arrayDealPage) let actualUBound = min(uBound, arrayDealPage.count - 1) for i in lBound...actualUBound{ 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) { // Only trigger load more if there's remaining data to load guard tempArray.count < arrayDealPage.count else { return } let lastItem = tempArray.count - 1 if indexPath.row == lastItem{ // Calculate the next range: start from current tempArray count, end at current count + batch size -1 let nextLowerBound = tempArray.count let nextUpperBound = nextLowerBound + loadBatchSize - 1 loadMoreData(lBound: nextLowerBound, uBound: nextUpperBound) } }
Key Improvements:
- Syntax Fix: Completed the upper bound calculation with a configurable
loadBatchSizefor flexibility. - Boundary Checks: Added
guardstatements to ensure we never attempt to access indices beyondarrayDealPage's length. - Prevent Duplicate Loads: The
guard tempArray.count < arrayDealPage.countcheck stops load-more calls once all data is loaded. - Safe Upper Bound Calculation: Using
min(uBound, arrayDealPage.count - 1)ensures we only load up to the last available item in the source array.
内容的提问来源于stack exchange,提问作者anuj tiwari

