Sort an array by NSDates using the sort function [duplicate]

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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?

回答1:

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


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