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