You can't use @FetchRequest in a function, but you absolutely can use a fetch request in a function. You just have to build an NSFetchRequest object, set its predicate and sort descriptors, then fetch it from a managed object context. Depending on exactly where that function is in your code, you may be able to access the managed object context without passing it explicitly into the function. It would go a bit like this:
func searchResults(searchingFor: String)
-> [Recipe] {
let recipeFetch = Recipe.fetchRequest()
recipeFetch.predicate = NSPredicate(format: "title CONTAINS[c] %@",searchingFor)
recipeFetch.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
let results = (try? self.managedObjectContext.fetch(recipeFetch) as [Recipe]) ?? []
return results
}
I haven't run this exact code, but it's very similar to code I'm using in several of my applications.
Topic:
Programming Languages
SubTopic:
Swift
Tags: