删除字典中的键并在 Swift 中重新加载 TableView 2

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

我正在创建一个在 ViewController 中有一个 UITableView 的应用程序。将在 TableView 中显示的数据在 NSDictionary 中。

让我解释一下我的项目是怎样的,然后问我的问题:

还有我的Swift代码:

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()
    }

}

当我点击“添加”按钮时,会按升序生成一个键(var count)和一个值 = "Row (1)." 这非常有效。

下一步是删除。添加了一个滑动来删除行,它完美地工作。

但是我用tableView.reload()为table充值时,显示错误

消息是:

fatal error: nil unexpectedly found while unwrapping an Optional value

我找到错误但无法修复的地方。

该错误是由于删除了 NSDicionary 中的一个键造成的。当我为我的 table 充值时,indexPath.row 获取数据字典 [indexPath.row],但此密钥不存在。

示例:如果删除key 2的行,重新加载table时,在字典中提取key 2的数据时会出现致命错误

我试图验证字典中是否有这样一个键,但是 table 显示了一个空行。我不需要显示任何行。

我的问题:当我们在TableView中使用keys和dictionaries时,如何return或不显示不存在的行?

这是一个元组数组,以防您真的想使用该 Int 值。如果你不需要它,那么就像其他人说的那样把它做成一个数组。

    @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()
    }