Удаление данных. Realm


#1

Привет! Есть такой экран:

Никак не могу корректно удалить данные из ячейки. Ситуация такая: при удалении первой ячейки в консоль выводится принт “Вторая удалена”, но удаляется первая. И так далее. Если я пытаюсь удалить данные из последней ячейки (пятой), то приложение падает с ошибкой, но запись все равно удаляется. Ошибка:

Terminating app due to uncaught exception ‘RLMException’, reason: ‘Index 4 is out of bounds (must be less than 4)’

Код всего контроллера:

class AllTasksTableViewController: UITableViewController {

let realm = try! Realm()

var tasks: Results<Task>!

@IBAction func cancel(segue: UIStoryboardSegue) {
    
}

override func viewWillAppear(_ animated: Bool) {
    readTaskAndUpdateUI()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tasks.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! AllTasksTableViewCell
    
    let bgColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).withAlphaComponent(0.8)
    cell.taskName.backgroundColor = bgColor
    cell.taskName.layer.cornerRadius = 4
    cell.taskName.clipsToBounds = true
    
    
    cell.taskDate.backgroundColor = bgColor
    cell.taskDate.layer.cornerRadius = 4
    cell.taskDate.clipsToBounds = true
    
    cell.taskName.text = tasks[indexPath.row].name
    cell.taskImage.image = UIImage(data: tasks[indexPath.row].image as Data)
    cell.taskDate.text = tasks[indexPath.row].createdAt
    
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)
}

override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let complete = UITableViewRowAction(style: .default, title: "Complete") { (action, indexPath) in
        self.realm.beginWrite()
        self.tasks[indexPath.row].isCompleted = true
        do {
            try! self.realm.commitWrite()
            print("Задача '\(self.tasks[indexPath.row].name) выполнена!'")
            self.tableView.reloadData()
        }
    }
    
    let delete = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in

        self.realm.beginWrite()
        self.realm.delete(self.tasks[indexPath.row])
        do {
            try! self.realm.commitWrite()
            print("Задача '\(self.tasks[indexPath.row].name) удалена!'")
        }
        tableView.deleteRows(at: [indexPath], with: .fade)
        self.tableView.reloadData()
    }
    
    complete.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)
    delete.backgroundColor = #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1)
    return [complete, delete]
}

func readTaskAndUpdateUI() {
    do {
        try realm.write {
            tasks = realm.objects(Task.self).filter("isCompleted = false")
            self.tableView.reloadData()
        }
    } catch let error as NSError {
        print("Не удалось загрузить данные. Ошибка - \(error.userInfo)")
    }
}
}