I use the following query in my app to filter Folders where the categories (array) id equals the one the user selected (categoryId
)
func getFoldersForCategory(_ categoryId:Int, sorting:String) -> Results<Folder> {
let realm = try! Realm()
let realmObjects = realm.objects(Folder.self).sorted(byKeyPath: "producerName", ascending: true).filter("toDate >= %@ AND language == %@", getCurrentLocalDateWithoutTimeStamp(), ApplicationSettingsRealm().getCurrentLanguage())
return realmObjects.filter({ $0.categories.filter({ $0.id == categoryId }) != [] })
}
The above code used to work when I returned an array of [Folder]
(hence getFoldersForCategory(_ categoryId:Int, sorting:String) -> [Folder]
.
I recently wanted to change the return to the results from the Realm query.
Now my code isn't working anymore, because I can't filter this way with Results<Folder>
. The error I receive is
Unable to infer closure type in the current context
So I was wondering if there is a way that I can convert the last line of code from an array to a Realm Results<>
Thanks!
No, you cannot. However, assuming that categories
is a Realm List
, you can simply include that filter in the query rather than converting it to an array:
func getFoldersForCategory(_ categoryId:Int, sorting:String) -> Results<Folder> {
let realm = try! Realm()
return realm.objects(Folder.self)
.sorted(byKeyPath: "producerName", ascending: true)
.filter("toDate >= %@ AND language == %@ AND ANY categories.id == %@",
getCurrentLocalDateWithoutTimeStamp(),
ApplicationSettingsRealm().getCurrentLanguage(),
categoryID)
}