NSFetchRequest Core Data Swift 3 Backward compatibility

Rox picture Rox · Sep 15, 2016 · Viewed 8.8k times · Source

I have converted my code in swift 3. I am using core data in my application. As you know, NSFetchRequest has been changed. In swift 2 it was:

let request = NSFetchRequest(entityName: "UnsyncedTask")

In swift 3:

let request:NSFetchRequest<NSFetchRequestResult> = UnsyncedTask.fetchRequest()

My question is, It only supports ios 10. How can I make it backward ios compatible? I want NSFetchRequest which supports ios 9, ios 10 with swift 3.

Answer

Martin R picture Martin R · Sep 15, 2016

NSFetchRequest(entityName:) is still available in Swift 3. You can use if #available to use the newer API on iOS 10/macOS 10.12 or later, and the older API on older OS versions:

let request: NSFetchRequest<UnsyncedTask>
if #available(iOS 10.0, OSX 10.12, *) {
    request = UnsyncedTask.fetchRequest()
} else {
    request = NSFetchRequest(entityName: "UnsyncedTask")
}
do {
    let results = try context.fetch(request)
    for task in results {
        // ...
    }
} catch let error {
    print(error.localizedDescription)
}