使用排序功能按NSDates对数组进行排序 [英] Sort an array by NSDates using the sort function
问题描述
我有一个名为Event
的模型类.
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
}
}
我从Web API获得事件数据作为JSON响应.然后,我通过解析JSON数据创建Event
对象,并将它们放入类型化数组(var events = [Event]()
)中.
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)
}
}
}
接下来,我需要按startDate
属性值对该数组进行排序.我尝试使用新的Swift标准库函数sort
这样对数组进行排序.
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.
无法使用类型为((__ _)-> _)'的参数列表调用'sort'
我不明白为什么我不能以这种方式对它进行排序,因为我有一个类型化的数组.
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?
推荐答案
您不能使用<
运算符直接比较日期.从那里,您有两种选择.首先,您可以使用NSDate的compare
函数.
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 })
另一种方法是获取日期的.timeIntervalSince1970
属性,该属性是可以直接比较的NSTimeInterval
:
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 })
这篇关于使用排序功能按NSDates对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!