title: Add and delete cell from table view in swift
body: <p>I have a table view in the cell i'm having two text fields in which user can enter the data. Initially i'm showing 5 cells. There is a button on which when user click it add one more cell in the table view. Now when i hit a button it add a cell when textfields are empty. But when i add data in all 5 cell textfields and than hit add button app crashes by showing this error, <code>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 10 into section 0, but there are only 6 rows in section 0 after the update'</code></p>
  
  <p>The code is try for adding and deleting cell is this, </p>
  
  <pre><code>extension FlashCardViewController: UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate{
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
      return numberOfCell
  }
  
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
      let cell = flashCardTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FlashCardTableViewCell
  
      //cell.termTxt.delegate = self
      //allCellsText[indexPath.row] = cell.termTxt.text!
     // cell.definitionTxt.delegate = self
      return cell
  }
  
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {
      return 115
  }
  
  func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -&gt; Bool {
      return true
  }
  
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
  
      if editingStyle == .delete{
          numberOfCell -= 1
          allCellsText.remove(at: indexPath.row)
          flashCardTableView.beginUpdates()
          flashCardTableView.deleteRows(at: [indexPath], with: .automatic)
          flashCardTableView.endUpdates()
      }
  }
  
  func textFieldDidEndEditing(_ textField: UITextField) {
      allCellsText.append(textField.text!)
      print(allCellsText)
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The code for add button is this,</p>
  
  <pre><code> @IBAction func addCardBtnTapped(_ sender: Any) {
  
      numberOfCell += 1
      let indexPath = IndexPath(row: allCellsText.count+1, section: 0)
      flashCardTableView.beginUpdates()
      flashCardTableView.insertRows(at: [indexPath], with: .automatic)
      flashCardTableView.endUpdates()
      view.endEditing(true)
  }
  </code></pre>
  
  <p>When i delete any cell it gives me error of index out of range. How can i achieve this goal? The view controllers looks like this,
  <a href="https://i.stack.imgur.com/MePy0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MePy0.png" alt="enter image description here"></a></p>