I'm using RealmSwift to query for appointments on a specific day, so the method looks like:
func appointments(on date: Date) -> [Appointment] {
realm.objects(Appointment.self)
.where {
Calendar.current.isDate($0.date, inSameDayAs: date)
}
.map { $0 }
}
But there are two issues:
Query<Date>
instead of Date
, how do I get the actual date from it?Query<Bool>
instead of Bool
, which isn't what I read on Realm's website regarding the query API: https://www.mongodb.com/developer/products/realm/realm-swift-query-api/What could possibly be wrong?
Thanks!
Realm queries only supports a subset of operations you can do in normal Swift. See this for a list of things it supports. This is enforced by using the Query<T>
type - it only declares the Realm-supported operations, like comparison operators, boolean operations, in
for collections, etc. You can't pass a Query<T>
around, as if it were a normal T
.
Determining whether a date is in the same day as another date is not one of the supported operations. What you can do instead is find the beginning and end of date
, and use comparison operators to check if the object's date
is between them.
let calendar = Calendar.current
let start = calendar.startOfDay(for: date)
let end = calendar.date(byAdding: DateComponents(day: 1), to: start)
.where { $0.date >= start && $.date < end }