Search code examples
iosswiftuitableviewcore-datadelete-row

Making only some rows deletable in a UITableView [Swift 3.0 - Xcode 8]


I have an array fruit = ["Apple", "Orange", "Pear", "Kiwi"] that has Entity FOOD and is presented in an UItableView. Is there a way to make some content undeletable. For example, can I make "Kiwi" undeletable.

Something like, let i = fruit.index(where: "Kiwi") let IArr = [0...fruit.count] IArr = IArr.filter{$0 != i} //deletes the index of Kiwi

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IArr) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    if editingStyle == .delete{
        let FRUIT = fruit[indexPath.row]
        context.delete(FRUIT)

        appDelegate.saveContext()
        do {
            fruit = try context.fetch(FOOD.fetchRequest())
        }
        catch
        {
            print("did not fetch")}
        }
        tableView.reloadData()}

However, this doesn't work because indexPath cannot take array types. How can I do this?


Solution

  • You can test that the row at the index path is not Kiwi:

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IArr) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext {
    
        let FRUIT = fruit[indexPath.row]
    
        if editingStyle == .delete && FRUIT != "Kiwi" {
            /* delete */
        }
    }