[英]Swift 5: index out of range when returning the array count from tableView numberOfRowsInSection
[英]SWIFT: Array index out of range' when calculating numberOfRowsInSection for tableView
我正在嘗試根據上一個屏幕上選擇的特定類別類型(例如,卧室裝飾,廚房用品,客廳家具等)計算numberOfRowsInSection。 我已經從上一屏幕使用prepareForSegue傳遞了一個索引,並使用以下內容來選擇類別類型:
let category = categoryData[index!]
let categoryType = category.category
然后,我將該類別類型與供應商數據結構進行交叉引用,以在tableView中顯示該特定類別的所有供應商。 以下是確定numberOfRowsInSection的函數:
//pulls the data from the Category and Vendor data structures which both contain a "category" item
let categoryData = Data().headerData
let vendorData = Data().vendorData
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let category = categoryData[index!]
let categoryType = category.category
var count: Int = 0
for (var i=1; i <= vendorData.count; i++) {
if vendorData[i].category == categoryType {
count = count + 1
}
}
return count
}
它可以成功運行,但是一旦進入供應商列表屏幕,它便崩潰並且控制台顯示“ Array index out of range”。 我在操場上進行了測試,看來效果很好。
對於整個上下文,一旦確定了正確的行數,我將運行以下命令來填充每個單元格:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("vendorCell", forIndexPath: indexPath) as! VendorSelectionTableViewCell
let category = categoryData[index!]
let categoryType = category.category
let vendorEntry = vendorData[indexPath.row]
if vendorEntry.category == categoryType {
cell.vendorName.text = vendorEntry.name
} else {
cell.vendorName.text = "No Value"
}
return cell
}
Swift數組從0開始計數,而不是從1開始計數。如果將代碼更改為
for (var i=0; i < vendorData.count; i++) {
if vendorData[i].category == categoryType {
count = count + 1
}
}
你應該沒事的。 我不確定為什么它可以在操場上工作。 也許您的vendorData
為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.