"まだ"の力 [Swift]基礎辞書

学んだことを書いていきます。質問やエラーなどございましたらお気軽にコメントお願いします。

セルが削除できないときはセクションごと削除する

環境

Xcode9.2
iOS11.0
Swift4

エラー内容

TableView内のセクション下の1つのセルを削除しようとした時にエラーが発生
イメージは下記サイトのトップの画像
UITableViewの行削除でセクション数が減るとクラッシュする - kaz29

以下解決した方法を載せます

エラーコード

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    
    let deleteButton: UITableViewRowAction = UITableViewRowAction(style: .normal, title: "削除") { (action, index) -> Void in
        self.array.remove(at: indexPath.section)
            
        tableView.deleteRows(at: [indexPath], with: .automatic)  //エラー
    }

    deleteButton.backgroundColor = UIColor.red
    return [deleteButton]
}

エラーメッセージ

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

原因

セルを削除するとnilのcellを持つセクションになるため落ちるみたい?

解決策

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
    let deleteButton: UITableViewRowAction = UITableViewRowAction(style: .normal, title: "削除") { (action, index) -> Void in
        self.array.remove(at: indexPath.section)
            
        //セクションごと削除
        //セルを削除するとnilのcellを持つセクションになるため落ちるみたい
        let indexSet = NSMutableIndexSet()
        indexSet.add(indexPath.section)
        tableView.deleteSections(indexSet as IndexSet, with: UITableViewRowAnimation.automatic )
        print("削除しました。\(self.array)")
    }

    deleteButton.backgroundColor = UIColor.red
    return [deleteButton]
}