Search code examples
swiftnspredicatefoundation

How to use NSPredicate with Date type


I am trying to make NSPredicate based on a date... I have tried this:

let datePredicate = NSPredicate(format: "due_date < %@", Date())

I am not sure, but iirc, this worked before?

Now I get this error:

Argument type 'Date' does not conform to expected type 'CVarArg'

I tried smth like this

... Date() as NSDate, but that failed too.

How to solve this?


Solution

  • To use the current date as a predicate parameter just create an NSDate instance

    let datePredicate = NSPredicate(format: "due_date < %@", NSDate())
    

    For a date variable you can use

    aDate as NSDate
    

    or

    aDate as CVarArg
    

    If you get the error

    'Date?' is not convertible to 'NSDate'

    then the code is not the real code because both Date() and NSDate() are non-optional.