Found Nil Optional Issue

Im using an API and displaying my data in a detailed tableview. My error is Fatal error: Unexpectedly found nil while unwrapping an Optional value. This is what I have, what should I do?

theSalary.text = "(item!.salary!)"
if (item!.salary!) == nil {
let message = "no salary listed"
theSalary.text = message
}

You want to use if let and optional chaining, instead of force-unwrapping.

1 Like

I think you need to rewrite your code, like this:

if let item = item, let salary = item.salary {
  theSalary.text = "\(salary)"
} else {
  theSalary.text = "no salary listed"
}

This will make sure your code doesn't crash when either item or salary are nil

2 Likes

Thank you that works.