3

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 get the events data from a web API as a JSON response. Then I create Event objects from parsing the JSON data and put them in an 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 the startDate property value. I tried sorting the array using the new Swift standard library function sort like this.

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

But strangely I get the following error.

Cannot invoke 'sort' with an argument list of type '((_, _) -> _)'

I don't understand why I cannot sort it this way because I have a typed array.

Any idea what I'm doing wrong here?

Isuru
  • 30,617
  • 60
  • 187
  • 303

1 Answers1

23

You can't directly compare dates using the < operator. From there, you have a couple options. First, you can use NSDate's compare function.

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

Another way is to get the date's .timeIntervalSince1970 property which is an NSTimeInterval which can be directly compared:

events.sort({ $0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970 })
Ian
  • 12,538
  • 5
  • 43
  • 62
  • I too was confused at the obscure error. Turns out it just means some sort of error inside the closure, thanks! – BradzTech Aug 02 '15 at 12:18