获取具有最新日期的对象

时间:2015-03-04 18:09:04

标签: ios swift nsdate

我有一组Thing类型的对象:

class Thing: NSObject {
    var data: String
    var type: String
   var created: NSDate
}

这些东西有一个名为created的NSDate属性。我的目标是编写一个函数来读取数组中每个东西的created属性,并返回具有最新日期的东西。该函数如下所示:

public func getLastSwipe(list: Array<Thing>) -> Thing {
    return someThing
}

3 个答案:

答案 0 :(得分:5)

如果您愿意,可以使用reduce。这将找到时间戳最高的对象。

var mostRecent = list.reduce(list[0], { $0.created.timeIntervalSince1970 > $1.created.timeIntervalSince1970 ? $0 : $1 } )

如果您的日期不是过去的日期,您还必须与当前日期进行比较以确定截止日期。如果您的日期都是以后的日期,则您需要将>切换为<以查找下一个未来日期(最低时间戳)。

答案 1 :(得分:2)

另一种方法是使用Swift&#39; .max,就像这样

let mostRecentDate = dates.max(by: {
   $0.timeIntervalSinceReferenceDate < $1.timeIntervalSinceReferenceDate
})

这是我发现的最高效的解决方案。

如果序列不为空,则返回序列的最近日期;否则,没有。

答案 2 :(得分:0)

您可以对数组进行排序,然后找到第一个/最后一个元素。例如......

let objects: [Thing] = ... //Set the array
let mostResent = array.sorted { (firstThing, secondThing) -> Bool in
    firstThing.created.timeIntervalSince1970 > secondThing.created.timeIntervalSince1970
}.first

这将返回最重新发送的Thing作为Optional(因为无法保证数组不为空。如果您知道该数组不为空,那么您可以使用.first!结束该行