From d37948276b2c1cce9b1c685125ef673dc9bf68e9 Mon Sep 17 00:00:00 2001 From: Gregory Higley Date: Thu, 27 Oct 2022 13:21:54 -0400 Subject: [PATCH] fetchFirst --- Sources/CoreDataQueryInterface/QueryBuilder+Fetch.swift | 4 ++++ Tests/CoreDataQueryInterfaceTests/Store.swift | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/CoreDataQueryInterface/QueryBuilder+Fetch.swift b/Sources/CoreDataQueryInterface/QueryBuilder+Fetch.swift index 336b811..6abf9ee 100644 --- a/Sources/CoreDataQueryInterface/QueryBuilder+Fetch.swift +++ b/Sources/CoreDataQueryInterface/QueryBuilder+Fetch.swift @@ -91,6 +91,10 @@ public extension QueryBuilder { try dictionaries().fetch(managedObjectContext) as! [[String: Any]] } + func fetchFirst(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> R? { + try limit(1).fetch(managedObjectContext).first + } + func count(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> Int { guard let moc = self.managedObjectContext ?? managedObjectContext else { preconditionFailure("No NSManagedObjectContext instance on which to execute the request.") diff --git a/Tests/CoreDataQueryInterfaceTests/Store.swift b/Tests/CoreDataQueryInterfaceTests/Store.swift index 562bf43..857c6b5 100644 --- a/Tests/CoreDataQueryInterfaceTests/Store.swift +++ b/Tests/CoreDataQueryInterfaceTests/Store.swift @@ -47,7 +47,7 @@ enum Store { let languageNames = info["ls"] as! [String] var languages: Set = [] for name in languageNames { - let language = try! moc.query(Language.self).filter { $0.name == name }.fetch().first! + let language = try! moc.query(Language.self).filter { $0.name == name }.fetchFirst()! languages.insert(language) } let developer = Developer(context: moc)