按日期swift排序自定义对象数组

时间:2015-08-25 13:53:05

标签: arrays swift sorting parse-platform nsdate

我有一个自定义对象“会议”我正在添加数组中的所有对象。我想要做的是从Meeting.meetingDate排序数组。

我也在使用Parse,我有两个查询并将结果放入一个数组中。

我可以将数据添加到“meetingData”,但不能对其进行排序。

任何人都可以帮忙吗?

所以我的数组是:

var meetingsData = [Meeting]()

会议班是:

public class Meeting: PFObject, PFSubclassing
{

  @NSManaged public var meetingTitle: String?
  @NSManaged public var meetingLocation: String?
  @NSManaged public var meetingNotes: String?
  @NSManaged public var meetingDuration: String?
  @NSManaged public var createdBy: User?
  @NSManaged public var meetingTime: NSDate?
  @NSManaged public var meetingDate: NSDate?

}

数组的内容如下:

<Meeting: 0x125edd040, objectId: xIqx7MoRd6, localId: (null)> {
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>";
meetingDate = "2015-08-29 17:07:12 +0000";
meetingDuration = "2 hours 2 mins";
meetingLocation = 4th Floor;
meetingNotes = With Investors;
meetingTime = "2015-08-24 09:00:17 +0000";
meetingTitle = Meeting with Investors;
}
<Meeting: 0x125ed95f0, objectId: tz4xx5p9jB, localId: (null)> {
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>";
meetingDate = "2015-08-23 23:00:00 +0000";
meetingDuration = "1 hour";
meetingLocation = "Emirates Stadium, London";
meetingNotes = "Football";
meetingTime = "2000-01-01 20:00:00 +0000";
meetingTitle = "Liverpool V Arsenal";
}
<Meeting: 0x125ed95f0, objectId: tz4xx5p9jB, localId: (null)> {
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>";
meetingDate = "2015-09-23 23:00:00 +0000";
meetingDuration = "1 hour";
meetingLocation = "Library";
meetingNotes = "Dev Team";
meetingTime = "2000-01-01 10:00:00 +0000";
meetingTitle = "Code Review";
}

我试图这样做Swift how to sort array of custom objects by property value但它不起作用

提前致谢

3 个答案:

答案 0 :(得分:51)

NSDate无法直接与<进行比较。您可以使用NSDate的{​​{3}}方法,如下面的代码所示:

meetingsData.sort({ $0.meetingDate.compare($1.meetingDate) == .OrderedAscending })

在上面的代码中,您可以使用compare枚举更改排序顺序,在Swift中实现如下所示:

enum NSComparisonResult : Int {
   case OrderedAscending
   case OrderedSame
   case OrderedDescending
}

我希望这对你有所帮助。

答案 1 :(得分:18)

Swift 3

meetingsData.sort(by: { $0.meetingDate.compare($1.meetingDate) == .orderedAscending})

OR

由于日期现在可以在 Swift 3 中直接比较,例如。

   let firstDate = Date()
   let secondDate = Date()

   if firstDate < secondDate {    
   } else if firstDate == secondDate {        
   } else if firstDate > secondDate {        
   }

答案 2 :(得分:6)

对于 Swift 4

按时间戳排序

values.sorted(by: { $0.meetingDateTimestamp > $1. meetingDateTimestamp})