删除单元格时的字典值 - 在展开Optional值时意外发现nil

时间:2017-02-07 17:41:06

标签: swift xcode uitableview dictionary

我在Swift / Xcode工作,我是应用程序开发的新手,我有一个带有2个标签的tableView。问题是删除tableView的单元格时。我需要获取其中一个单元格标签的数据,但应用程序崩溃时会出现致命错误 - 在展开“可选”值时意外发现nil

我已经设置了断点,以便我可以检查字典中是否存有任何内容,它确实存在,其中存储了一个元素。

感谢任何帮助

 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
  if editingStyle == UITableViewCellEditingStyle.Delete {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! myCustomCell

       self.cost = self.total
      // This line gives me the error** self.total = self.cost - self.dict[cell.cellPrice.text!]!
       self.totalLabel.text = "Total: \(self.total)"

       self.dict.removeValueForKey(cell.cellTitle!.text!)
       tableView.reloadData()
       saveState()



}

这是我设置单元格的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
   let cell: myCustomCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! myCustomCell 
   var myDataSource : [String] = Array(self.dict.keys) 
   let key = myDataSource[indexPath.row] as String 
   cell.cellTitle?.text = myDataSource[indexPath.row] 
   cell.cellPrice?.text = "£(self.dict[key]!)"
   self.saveState() 
   return cell 
}

2 个答案:

答案 0 :(得分:1)

我必须看到更多代码才能知道如何设置newArr[t]===newArr[p]的属性,但看起来t为零或p为零。你应该安全地打开那些选项,而不是试图强迫它们。这看起来像这样:

myCustomCell

一般情况下,你应该远离力量展开(使用!),除非你只是为了测试或其他东西而快速写作。它使调试更加困难。

答案 1 :(得分:0)

你正试图强行打开包装。我猜它是cellPrice标签或文本但是其中之一。找出哪一个是零。