I am trying to figure out how Swift 3 handles unwrapping with the if let syntax. My scenario is I want to make a fetch from CoreData in an if let statement. I want to unwrap the value there and if there is a value (not nil), then use it. If there is not a value, perform what is in the else block. Seems to make sense, but in my experience this is not what Swift 3 thinks.
NOTE: there are NO "Object" entities to be returned. I WANT it to drop down to print "No Objects".
CODE
// How I'm making the fetch from CoreData
class func getAllObjects() -> [Object]? {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest<Object>(entityName: "Object")
let fetched = try! context.fetch(fetchRequest)
return fetched
}
// Unwrapping value: How I'd do it... But Xcode didn't like...
if let fetchedObjects = WorkOrder.getAllObjects() as? [Order] {
self.objects = fetchedObjects
}
else {
print("No Objects")
}
// Unwrapping value: How Xcode "corrected" my code and this compiles
if let fetchedObjects = WorkOrder.getAllObjects()! as [Order]? {
self.objects = fetchedObjects
}
else {
print("No Objects")
}
WHAT HAPPENS
The app crashes. It found nil while unwrapping an option value. I thought the if let was supposed to guard against my app crashing. Because if there isn't anything valid to unwrap it should execute the else block. Right?
QUESTION
Do you know of a way to have if let to behave in the way I suggested above? Or code that will behave as such?
Aucun commentaire:
Enregistrer un commentaire