Dictionary value when deleting cell - unexpectedly found nil while unwrapping an Optional value

V.Roberts Source

Im working in Swift/Xcode and I am new to app development, i have a tableView with 2 labels. The issue is when deleting a cell of my tableView. I need to get the data of one of the cell labels but the app crashes with the fatal error - 'unexpectedly found nil while unwrapping an Optional value'

I have set up break points so that i can check if the dictionary has anything stored in it, which it does, there is an element stored in it.

Appreciate any help

 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)"



This my code to set up the cell:

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]!)"
   return cell 


answered 1 year ago K. Michał #1

You are trying to force unwrap. I guess it's cellPrice label or it text but one of those things. Figure out which one is nil.

answered 1 year ago creeperspeak #2

I'd have to see more of your code to know how you are setting properties of myCustomCell, but it looks like either cellPrice.text is nil or self.dict[cell.cellPrice.text] is nil. You should just unwrap those optionals safely rather than trying to force them. That'd look something like this:

if let price = cell.cellPrice.text, let priceValue = self.dict[price] {
    self.totalLabel.text = "Total: \(priceValue)"

In general you should stay away from force unwrapping (using !) unless you're just writing really quickly for testing or something. It makes debugging harder.

comments powered by Disqus