swiftrealmnspredicatepredicate

Convert value to compare in NSPredicate


I am trying to use NSPredicate with Swift and RealmSwift. I want to filter a Realm collection, with one predicate being date related. The dates are stored as Strings in the format yyyy-MM-dd — how do I convert this to a Date so I can compare it to today, as part of the predicate?

My [non-working] attempt so far:

let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let datePredicate = NSPredicate(format: "nextReview <= %@", argumentArray: [today, dateFormatter]) {
    let nextReviewDate = dateFormatter.date(from: $0.nextReview)
    return nextReviewDate ?? today <= today
}

...

var cardsToReview: [RealmCard] = Cards.filter(compoundPredicate).map { $0 }

Solution

  • You are making things more complicated than needed. Since you have the date format "yyyy-MM-dd" in your database you can directly compare the strings since they will always have the same order as when converted to dates.

    let today = dateFormatter.string(from: .now)
    let datePredicate = NSPredicate(format: "nextReview <= %@", today)