Sorting NSDates array using sort function

I have a model class called Event

.

import Foundation
import MapKit

public class Event {

    let id: Int
    var title: String?
    let status: String
    let location: String
    var description: String?
    var latitude: CLLocationDegrees?
    var longitude: CLLocationDegrees?
    var startDate: NSDate?
    var endDate: NSDate?


    init(id: Int, location: String, status: String) {
        self.id = id
        self.location = location
        self.status = status
    }

}

      

I am receiving event data from web API as JSON response. Then I create objects Event

to parse the JSON data and put them in a typed array ( var events = [Event]()

).

private func processEventData(data: JSON) {
    var events = [Event]()

    if let eventsArray = data.array {
        for eventObj in eventsArray {
            let event = Event(
                id: eventObj["id"].int!,
                location: eventObj["location"].string!,
                status: eventObj["status"].string!
            )
            event.title = eventObj["title"].string
            event.description = eventObj["description"].string
            event.latitude = eventObj["lat"].double
            event.longitude = eventObj["lng"].double
            event.startDate = NSDate(string: eventObj["start"].string!)
            event.endDate = NSDate(string: eventObj["end"].string!)

            events.append(event)
        }

    }
}

      

Next, I need to sort this array by property value startDate

. I tried to sort the array using the new Swift standard library function sort

like this.

var orderedEvents = events.sort({ $0.startDate! < $1.startDate! })

      

But strangely I am getting the following error.

Can't call 'sort' with an argument list like '((_, _) -> _)'

I don't understand why I can't sort it like this, because I have a typed array.

Any idea what I am doing wrong here?

+3


source to share


1 answer


You cannot directly compare dates using an operator <

. From there, you have a couple of options. First, you can use the NSDate function compare

.

events.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending })

      



Another way is to get the date property .timeIntervalSince1970

, which is NSTimeInterval

, which can be compared directly:

events.sort({ $0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970 })

      

+22


source







All Articles