0

Months ago I wrote this app that retrieves data from Firebase and show them in TableViewCell. Opening the project today I'm facing this

fatal error: unexpectedly found nil while unwrapping an Optional value

Actually I don't know what to do.

The lines of code that generates the problem are the follow:

if snapshot.exists()
{
 self.acceptedQuests.append(InfoQuest(rest.key, quest?["name"] as! String, quest?["description"] as! String, quest?["image"] as! String))
 print(self.acceptedQuests.count)
 self.tableView!.reloadData()
}

Any help will be really appreciated.

rulezzer
  • 55
  • 8

1 Answers1

0

Your error is either occurring when you are casting the quest elements, or when referencing the table view. I would be surprised if your table view was nil so it was probably happening when you are casting. This is an example where a guard statement would work really well

if snapshot.exists()
{
   guard let name = quest?["name"] as? String,
         let description = quest?["description"] as? String,
         let image = quest?["image"] as? String,
         let tableView = self.tableView else
         {
            // One of those values was either nil or could not become a String
           return
         }
   self.acceptedQuests.append(InfoQuest(rest.key, name, description, image))
   print(self.acceptedQuests.count)
   tableView.reloadData()
}

This will stop you from accessing a nil item. If any of the casts fail or any value is nil the else block will execute and return

Garrigan Stafford
  • 1,331
  • 9
  • 20