You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中TableView报Thread 1: Index out of range错误求助

Swift JSON移动后数组越界问题解决

问题描述

原本可正常运行的Swift代码,仅整理并移动JSON文件后,在return questions[questionCount].question.count行频繁触发Thread 1: Fatal error: Index out of range错误,重新实现JSON解析仍无法解决。

解决方案

1. 确认JSON文件已正确加入Target

移动文件后最常见的问题是JSON未被添加到当前项目的Target中,导致Bundle.main.path返回nil,最终questions数组为空,访问questions[questionCount]直接越界。

  • 操作步骤:选中JSON文件,查看右侧Inspector面板的Target Membership,确保勾选了当前运行的Target;
  • 也可在Build Phases -> Copy Bundle Resources中检查是否包含该JSON文件,若没有则点击+添加。

2. 增强JSON解析的错误处理与有效性检查

原解析逻辑中,若文件找不到或解析失败,questions数组会保持空值,但后续代码仍会直接访问数组元素,导致崩溃。修改parseJson方法,增加解析后的空值校验:

private func parseJson(){
    guard let path = Bundle.main.path(forResource: "Fragen_Funktional", ofType: "json") else {
        print("JSON文件未找到")
        return
    }
    let url = URL(fileURLWithPath: path)
    
    do {
        let jsonData = try Data(contentsOf: url)
        let parsedQuestions = try JSONDecoder().decode([Questions].self, from: jsonData)
        guard !parsedQuestions.isEmpty else {
            print("JSON解析结果为空")
            return
        }
        questions = parsedQuestions
        // 解析成功后再刷新表格
        loadData()
    } catch {
        print("JSON解析错误: \(error)")
    }
}

注意:将loadData()移到解析成功后调用,避免表格在questions为空时刷新。

3. 给UITableView数据源方法添加安全防护

在访问数组元素前,先校验索引的有效性,避免越界。同时可以给数组添加安全下标扩展,简化判断:

第一步:添加数组安全下标扩展

在项目任意位置添加:

extension Collection {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

第二步:修改数据源方法

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // 先校验questionCount是否在questions的有效范围内
    guard let currentQuestion = questions[safe: questionCount] else {
        return 0
    }
    // 再校验currentQuestion的question属性是否有效(根据你的模型调整,若question是String则count是字符数,若为数组则是元素个数)
    return currentQuestion.question.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let currentQuestion = questions[safe: questionCount] else {
        return UITableViewCell()
    }
    let text = currentQuestion.question
    let cell = tableView.dequeueReusableCell(withIdentifier: "Fragen3", for: indexPath) as! TableViewCellQuestion_3
    
    cell.unterFragenLabel.text = currentQuestion.questionpoints[safe: indexPath.row]?.description ?? ""
    antwortLabel.text = text
    cell.button_Ja.tag = indexPath.row
    cell.delegate = self
    
    cell.button_Ja.isEnabled = true
    cell.button_nein.isEnabled = true
    cell.selectionStyle = .none
    cell.actionBlockYes = {
        cell.button_Ja.isEnabled = false
        cell.button_nein.isEnabled = true
    }
    cell.actionBlockNo = {
        cell.button_nein.isEnabled = false
        cell.button_Ja.isEnabled = true
    }
    cell.backgroundColor = .white
    return cell
}

4. 验证JSON结构与模型匹配

移动文件时若不小心修改了JSON内容,可能导致解析后的Questions实例属性异常(比如question字段缺失或类型不匹配)。对比之前能正常运行的JSON版本,确认:

  • JSON数组的元素数量是否正确;
  • 每个元素的question、questionpoints字段是否存在且类型与Questions模型一致;
  • 模型的CodingKeys(若自定义)是否与JSON键名完全匹配。

内容的提问来源于stack exchange,提问作者user18506050

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:48:22