1

I would like to filter my custom objects with a date property.

For example:

class Event
{
    let dateFrom: NSDate!
    let dateTo: NSDate!

    init(dateFrom: NSDate, dateTo: NSDate) {
        self.dateFrom = dateFrom
        self.dateTo = dateTo
    }
}

Now i have a List of maybe 500 Events, and i just want to show the Events for a specific date. I could loop through all Objects, and create a new Array of Objects, but could i also use a filter?

Ill tried something like this:

let specificEvents = eventList.filter( { return $0.dateFrom > date } )

Where date is a NSDate Object for a specific date, but i am not able to use the > operater.

Is there an easy way to get all the events for a specific date, where the date is between the dateFrom and dateTo period?

derdida
  • 14,784
  • 16
  • 90
  • 139

2 Answers2

5

Thanks to Martin for pointing me into the right direction.

Here is an answer if someone else is looking how to solve this in Swift:

Add an Extension to NSDate:

public func <(a: NSDate, b: NSDate) -> Bool {
    return a.compare(b) == NSComparisonResult.OrderedAscending
}

public func ==(a: NSDate, b: NSDate) -> Bool {
    return a.compare(b) == NSComparisonResult.OrderedSame
}

extension NSDate: Comparable { }

So you are able to use the < and > operator for NSDate comparison.

    var date = dateFormatter.dateFromString(dateString)
    var dateTomorrow = date?.dateByAddingTimeInterval(NSTimeInterval(60*60*24)) // add one Day

    eventsToday = allEvents.filter( { return $0.dateFrom >= date && $0.dateTo < dateTomorrow} )
derdida
  • 14,784
  • 16
  • 90
  • 139
0

For Swift 3.x update :-

extension Date: Comparable{
   public static func <(a: Date, b: Date) -> Bool{
        return a.compare(b) == ComparisonResult.orderedAscending
    }
    static public func ==(a: Date, b: Date) -> Bool {
        return a.compare(b) == ComparisonResult.orderedSame
    }
}
gamal
  • 1,587
  • 2
  • 21
  • 43