Search code examples
iosswiftcore-datansfetchrequest

executeFetchRequest fatal error in Swift


I'm new to Swift and I'm trying to learn while I write some Core Data related methods. I need to fetch some entities, this is a code snippet of the method I call for that:

let results = context.executeFetchRequest(fetchRequest, error: &error) as! [MyCustomEntity]?
    if let myEntities = results {
        let lastEntity = myEntities.last!
        return lastEntity.entityNum.integerValue
    }

When I run the app, it crashes at the line let lastEntity = myEntities.last! and I get this message in console:

fatal error: unexpectedly found nil while unwrapping an Optional value

However, error is nil at that point. I followed an example to write that code, and as far as I understood, the if statement block should only be executed if there are results... right? What is it happening there?

Thanks in advance


Solution

  • I'm assuming that the array that you're receiving is empty. You are using optional binding correctly to determine whether you receive an array or not, but that does not guarantee that you have elements in the array.

    The last method on Array returns an Optional; it returns nil when the array is empty:

    /// The last element, or `nil` if the array is empty
    var last: T? { get }
    

    You are unwrapping the return value from myEntities.last, which means your app crashes when myEntities is an empty array.

    To make this code safe you'll additionally need to check the return value from the last method.