Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the object with the most recent date

Tags:

ios

swift

nsdate

I have an array of objects of type Thing:

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

These things have an NSDate property called created. My aim is to write a function that reads the created property of every thing in the array and returns the thing that has the most recent date. The function looks like this:

public func getLastSwipe(list: Array<Thing>) -> Thing {
    return someThing
}
like image 545
Marc Avatar asked Dec 01 '22 00:12

Marc


2 Answers

Another approach is using Swift's .max, like this

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

This is the most performant solution I've found.

Returns the sequence’s most recent date if the sequence is not empty; otherwise, nil.

like image 95
Oscar Apeland Avatar answered Dec 28 '22 16:12

Oscar Apeland


You could use reduce if you wanted. This will find the object with the highest timestamp.

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

If your dates are not all in the past, you'll have to also compare against the current date to determine a cutoff. If your dates are all in the future, you'll want to switch the > to < to find the next future date (lowest timestamp).

like image 37
Ian MacDonald Avatar answered Dec 28 '22 17:12

Ian MacDonald