Swift 2.0 Snippet: CoreData fetching with error handling

I have just downloaded the first Xcode 7 beta and started converting one of my playground projects to Swift 2.

Tip: Branch your code before starting a migration and don’t forget to commit all your changes before branching.

After the migration work was done I was left with a bunch of errors to fix. One of them was related to the way I was fetching from the CoreData. My code looked like this:

func getGalleryForItem(item: Item)-> [Image]? {
  var fetchRequest = NSFetchRequest(entityName: "Image")
  var predicate = NSPredicate(format: "%K == %@", "item", item)
  fetchRequest.predicate = predicate

  var fetchError:NSError? = nil

  if let fetchResults = self.managedObjectContext?.executeFetchRequest(fetchRequest, error: &fetchError) as? [Image] {
    if fetchError != nil {
      println("getGalleryForItem error: \(fetchError!.localizedDescription)")
    }
    return (!fetchResults.isEmpty) ? fetchResults : nil
  } else {
    if fetchError != nil {
      println("getGalleryForItem error: \(fetchError!.localizedDescription)")
    }
    return nil
  }
}

And here’s how the Swift 2.0-compatible version of the above looks like – quite neat I should say!

func getGalleryForItem(item: Item)-> [Image]? {
  let fetchRequest = NSFetchRequest(entityName: "Image")
  let predicate = NSPredicate(format: "%K == %@", "item", item)
  fetchRequest.predicate = predicate

  // here's the sugar
  do {
    let fetchResults = try self.managedObjectContext?.executeFetchRequest(fetchRequest) as? [Image]
    return fetchResults
  } catch let fetchError as NSError {
    print("getGalleryForItem error: \(fetchError.localizedDescription)")
    return nil
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *