Swift filter by NSDate object property

烂漫一生 提交于 2020-01-03 03:25:12

问题


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?


回答1:


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} )



回答2:


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
    }
}


来源:https://stackoverflow.com/questions/29095950/swift-filter-by-nsdate-object-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!