NSPredicate and string interpolation

While adding a fetch request to check for previously downloaded photos, I was never able to find any, Using the debugger I was able to narrow it down, my fetch request was never returning any results.
if let existingPhoto = fetchedPhotos?.first { return existingPhoto } //never true!

Doing some digging I found that NSFetchRequest objects had a method that could print a description of the fetch request in a very readable format: photoID == "36815039393"

This looked like it should have but for whatever reason, there were never any matches. After some googling, I found documentation which said that String interpolation:
"Interpolation example: \(someVariable)"

Should be avoided with fetch requests, and that substitution syntax is preferred. Directly passing in the photoID that was returned from the web service as an argument was what finally got my code running.
let predicate = NSPredicate(format: "\(#keyPath(Photo.photoID)) == %@", photoID)

For anyone else having issues with their code not returning existingPhotos from their fetchRequest, this might be a good place to start.

Just for reference, Iā€™m building with Xcode 9 from macOS High Sierra to iOS11

Hope this helps!

1 Like