我有一个 桌景 我试图将一个单元格从一个区域移动到另一个区域。然而,当我尝试这样做时,我得到的是一个关于 "移动 "的对话框。'Fatal Error: Index out of range'
在线上。goals[1].append(goals[0][indexPath.row])
.
这是我的代码。
import UIKit
class GoalsViewController: UIViewController {
@IBOutlet weak var goalTableView: UITableView!
let sections: [String] = ["Mark as Complete:", "History:"]
var goals: [[String]] = [] //This is like this because the cell is also transported from another table view in a separate view controller to this table view.
let theEmptyModel: [String] = ["No data in this section."]
extension GoalsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if goals.indices.contains(section) {
return goals[section].count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TodayGoalViewCell_1", for: indexPath) as? GoalTableViewCell
cell?.goalLabel.text = goals[indexPath.section][indexPath.row]
cell?.cellDelegate = self
cell?.index = indexPath
return cell!
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
progressBarAnimation()
if goals[0] != theEmptyModel {
goals[1].append(goals[0][indexPath.row])
if goals[1].first!.contains("No data in this section.") {
goals[1].removeFirst()
}
goals[0].remove(at: indexPath.row)
if goals[0].count == 0 {
goals[0].append(contentsOf: theEmptyModel)
}
tableView.reloadData()
}
}
其中一些下标调用失败 goals[1]
或 goals[0]
或 [indexPath.row]
- 尝试调试或打印数组。为了避免硬崩溃,请使用 get()
从这个扩展。
extension Array {
func get(_ index: Int) -> Element? {
if 0 <= index && index < count {
return self[index]
} else {
return nil
}
}
}
使用 guard
在您的方法的开头进行检查,或 if
声明: