0

Getting crash in some iPhone device not all and the crash is pointing out this line and message is showing "Unexpectedly found nil while unwrapping an Optional value". Below is the swift code

let location = userDefaults.object(forKey: "itemRes") as! [String] //this line is getting crash
requestModel.second_res_lat = location[0].description
requestModel.second_res_lon = location[1].description
Mohammed Nabil
  • 137
  • 1
  • 6
  • https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu – Shehata Gamal Apr 13 '21 at 18:06
  • 1
    `userDefaults.object(forKey: "itemRes")` can't be converted to an array of Strings – aheze Apr 13 '21 at 18:07
  • @aheze Some devices not getting crash and some devices getting crash, so what is the solution to fix this issue ? – Mohammed Nabil Apr 13 '21 at 18:10
  • Instead of force-unwrap, use guard: `let location = userDefaults.object(forKey: "itemRes") as? [String] else { /* No such setting, or it cannot be converted to array of strings */ return }`. – timbre timbre Apr 13 '21 at 18:11
  • @MohammedNabil try `print("itemRes is \(userDefaults.object(forKey: "itemRes"))")` to see what it is. It might not be what you are expecting – aheze Apr 13 '21 at 18:12
  • @aheze the device which is not getting crash, the print result is `["24.69759", "46.68704"]` – Mohammed Nabil Apr 13 '21 at 18:17

1 Answers1

1

This crashes because user defaults either doesn't have the value i.e it's nil or it's not the same type. Best practice is always to use optional binding to eliminate the chance of an exception.

This assumes that user defaults will always have the value of the correct type: let location = userDefaults.object(forKey: "itemRes") as! [String]

Try unwrapping the value safely before proceeding like so:

if let location = userDefaults.object(forKey: "itemRes") as? [String] {
   requestModel.second_res_lat = location[0].description
   requestModel.second_res_lon = location[1].description
} else {
   // No location value found
}

OR

guard let location = userDefaults.object(forKey: "itemRes") as? [String] else { return }
requestModel.second_res_lat = location[0].description
requestModel.second_res_lon = location[1].description

This may also be useful: https://developer.apple.com/documentation/swift/optional

Owen
  • 791
  • 1
  • 3
  • 14
  • This is really strange i am not getting crash but problem is some devices print is showing some value and some devices the print is showing `nil` – Mohammed Nabil Apr 13 '21 at 18:35
  • @MohammedNabil It sounds like this is related to a previous question you've asked. Go through your code and make sure that you don't try to read `"itemRes"` from user defaults before it's been set. You can use the top piece of code in the answer and that will certainly stop the crash. You just need to find out why it's being read when it's not been set. – Owen Apr 13 '21 at 18:43