Reputation: 77
Hi i want to filter results by year number in realm, I did something but its return type is LazyFilterCollection<>. How can i fix it to get Results? I think it could be done using NSPredicate, but I can't understand how to use date component in predicates.
Here is my Training model.
class Training: Object {
@objc dynamic var id = 0
@objc dynamic var date = NSDate()
var exercises = RealmSwift.List<TrainingExercise>()
convenience init(date: NSDate, exercise: TrainingExercise) {
self.init()
self.exercises.append(exercise)
}
override class func primaryKey() -> String? {
return "id"
}
}
And here is expression where i'm trying to filter it.
let trainingsFilteredByYear = trainings.filter {
return Calendar.current.component(.year, from: $0.date as Date) == 2018
}
Upvotes: 3
Views: 2051
Reputation: 332
Unfortunately it's not that simple. Results.filter takes nspredicate or a predicate format string.
let trainingsBetweenDates = realm.objects(Trainings.self).filter("date BETWEEN {%@, %@}", startDate, endDate)
you can make the boundary dates yourself using the methods described here:How do you create a swift Date object
Upvotes: 4