How to exclude TableViewCell being a Swift Dictionary

2

I'm trying to delete a TableViewCell using the swipe to delete style, but I can not delete the cells. The cells are being created by a dictionary that creates each one with the key as a title and value as details.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    //Cria as cells pelo dicionário favDict
    for (key, value) in favDict{
        cell.textLabel?.text = key
        cell.detailTextLabel?.text = value
    }

    return cell
}

func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        favDict.removeAtIndex(indexPath!.row) //Linha em que esta dando o erro, aparece que Int não é convertido para [String: String]
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}
    
asked by anonymous 02.01.2015 / 19:03

2 answers

0

The problem will be access to indexPath . You are forcing optional unboxing with ! . In the method definition, indexPath: NSIndexPath! is already automatically doing the unboxing so just have to use it normally:

Example:

lista.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    
03.01.2015 / 07:04
0

The problem is that you are removing an item from Dictionary in the wrong way.

First, you are passing an integer to a method that does not accept integer:

The removeAtIndex method, in the case shown, expects a parameter of type DictionaryIndex<String, String> that can be obtained using the indexForKey method.

Second, the dictionary is a Key - > Value , so to delete an item, you need to enter the key related to that value.

So to be able to delete an item from your dictionary, you first need to find the key related to that position in the table.

let keyArray = Array(favDict.keys)
let key = keyArray[indexPath.row]
favDict.removeValueForKey(key)
    
23.01.2016 / 17:16