Reputation: 3736
I would like to filter some Realm results in Swift based on a date and a number of days. I have a Realm Object that has the following properties:
class Route: Object, ObjectKeyIdentifiable, Codable {
@Persisted(primaryKey: true) var id: Int?
@Persisted var status: String?
@Persisted var bucket_name: String?
@Persisted var frequency_days: Int?
@Persisted var last_record_date: Date?
}
And what I would like to do is add the number of days in frequency_days
to the last_record_date
while I am filtering the results.
In my View I would like to do something like this (I know you can't add an Int to a Date, but this is just to illustrate my goal):
self.filteredRoutes = self.routes.where {
($0.last_record_date + $0.frequency_days < Date())
}
I also couldn't find anything in the filter section of the docs
I'm not even sure if this is possible, but if anyone has some ideas to get this to work or a work around, it would be appreciated.
Upvotes: 0
Views: 311
Reputation: 35658
I would suggest just storing the actual date you want to query against.
You know the last_record_date and the frequency_days so why not add them together and store that as a date.
For example;
Suppose the last_record_date is 2022-04-01 and frequency_days is 10 (days).
If you add the number of days onto last_record_date, the resultant date is 2022-04-10 (including the 1st).
So store that at a target_date property: 2022-04-10
Any time the either the frequency date or last_record_date changes you can simply calculate a new target date and store that.
I would suggest adding a function to you Realm class to do that for you, and if you need to store the frequency_days and last_record_date you can do that as well.
class Route: Object, ObjectKeyIdentifiable, Codable {
@Persisted(primaryKey: true) var id: Int?
@Persisted var frequency_days: Int?
@Persisted var last_record_date: Date?
@Persisted var target_date: Date?
func changeFrequencyDays(newDayCount: Int) {
self.frequency_days = newDayCount
//do some math to add newDayCount to the last_record_date
self.target_date = //new calculated date
}
func changeLastRecordDate(lastRecordDate: Date) {
self.last_record_date = lastRecordDate
//do some math to add frequency_days to the new lastRecordDate
self.target_date = //new calculated date
}
}
With the above, any time a frequency_days need to be updated or the last_record_date changes, call the appropriate function and that property will be updated along with updating the target_date property.
Upvotes: 1