Search code examples
swiftuitableviewswift2nsdictionarynsindexpath

Remove a key in the Dictionary and reload a TableView in Swift 2


I am creating an app that has a UITableView in a ViewController. The data that will be presented at TableView are in an NSDictionary.

Let me explain how my project is to then ask my question: enter image description here

And my Swift Code:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!

    var dict:[Int:String] = [:]
    var count:Int = 0

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

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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCell
        cell.label.text = self.dict[indexPath.row]! as String
        return cell
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            let alert = UIAlertController(title: "Remove?", message: "Touch in Remove", preferredStyle: .Alert)
            let remove =  UIAlertAction(title: "Remove", style: UIAlertActionStyle.Destructive) { (UIAlertAction) -> Void in
                self.dict.removeValueForKey(indexPath.row)
                self.tableView.reloadData()
            }
            let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

            alert.addAction(cancel)
            alert.addAction(remove)
            self.presentViewController(alert, animated: true,completion: nil)
        }
    }

    @IBAction func addAction(sender: AnyObject) {
        dict[count] = "Row \(count)"
        ++count
        self.tableView.reloadData()
    }

}

When I tap the Add button, a key is generated in ascending order (var count) and a value = "Row (1)." This is working perfectly.

The next step is for removal. Added a Swipe to remove the row and it works perfectly.

However, when I recharge the table by tableView.reload (), an error is displayed.

The message is:

fatal error: nil unexpectedly found while unwrapping an Optional value

I found where the error but I can not fix occurs.

The error is a result of removing a key in NSDicionary. When I recharge my table, indexPath.row takes the data dict[indexPath.row], but this key does not exist.

Example: If you remove the line with the key 2, when reloading the table, the fatal error will occur when you pick up the key 2 data in the dictionary.

I tried to validate that there is such a key in the dictionary, but the table displays an empty line. And I need not display any rows.

My question: When we work with keys and dicionaries together with the TableView, how can we return or not to display a nonexistent line?


Solution

  • Here you go an array of Tuples, incase you really wanted to use that Int value. If you don't need it then just make it an array like others said.

        @IBOutlet var tableView: UITableView!
        var tuple = [(Int,String)]()
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return tuple.count
        }
    
            cell.label.text = tuple[indexPath.row].1
            return cell
        }
    
    
        self.dict2.removeAtIndex(indexPath.row)
    
    
        @IBAction func addAction(sender: AnyObject) {
            tuple += [(count,"Row \(count)")]
            ++count
            self.tableView.reloadData()
        }