首页 > 解决方案 > 如何解决二维数组中的“线程 1:致命错误:索引超出范围”

问题描述

启动我的应用程序“线程 1:致命错误:索引超出范围”时发生崩溃。完整错误:

Fatal error: Index out of range: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444
2020-07-11 14:04:40.909080+0200 Carrot[13983:705959] Fatal error: Index out of range: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444
(lldb) 

谁能告诉我如何解决这个错误?我在这一行收到错误:

return twoDArray[section].items.count

这是我完整的 ViewController 文件:

class TableViewController: UITableViewController, AddTask, ChangeButton {
    
var sections = FoodData.foodCategories

var twoDArray = [
    Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]), Section(isExpanded: true, items: [Task(name: "No items yet")]),
    ]

// MARK: - TableView data source

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    if section == 0 {
        return 1
    }
    
    return twoDArray[section].items.count
}

这是 FoodData 结构:

struct FoodData {
static let foodCategories = ["New item", "Produce ", "Meat ", "Breakfast ", "Seafood ", "Dairy ", "Frozen ", "Drinks ", "Snacks ", "Grains", "Cans & Jars ", "Spices", "Sauces & Oils", "Paper", "Cleaning", "Personal", "Baking ", "Other"]

}

标签: iosswiftuitableviewindexoutofrangeexception

解决方案


问题是由您未显示的代码引起的。您在 中返回的数字太大numberOfSections


推荐阅读