I have an array of dates. I need to find the latest one. Can someone show me an example?
You can make NSDate
conform to Comparable
, as shown here
Given this, you can then use maxElement
to find the maximum (ie the latest).
import Foundation
extension NSDate: Comparable { }
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
let dates = [NSDate(), NSDate()]
let maxDate = maxElement(dates)
Note, maxElements
goes bang for empty arrays so you may want to guard it with isEmpty
:
let maxDate = dates.isEmpty ? nil : Optional(maxElement(dates))
Or, if you don't want to go the extension route:
if let fst = dates.first {
let maxDate = dropFirst(dates).reduce(fst) {
$0.laterDate($1)
}
}
or, to return an optional:
let maxDate = dates.reduce(nil) {
(lhs: NSDate?, rhs: NSDate?)->NSDate? in
lhs.flatMap({rhs?.laterDate($0)}) ?? rhs
}
You can make use of reduce
:
guard let dates = dates, !dates.isEmpty else { return nil }
dates.reduce(Date.distantPast) { $0 > $1 ? $0 : $1 }
Edit: Handle empty or nil array
Swift has Array methods for getting both the min and max values for dates.
You can use the following:
let maxDate = myArrayOfDates.max()
let minDate = myArrayOfDates.min()
So if you have an array of dates like so:
And here is the code if you want to copy it:
let now = Date()
let dates = [
now,
now.addingTimeInterval(120),
now.addingTimeInterval(60)
]
let sut = dates.max()
print(sut!)
Hope this helps someone!
Run this in your playground
var dates = [NSDate]() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let date1 = dateFormatter.dateFromString("02-06-1987") let date2 = dateFormatter.dateFromString("02-06-2001") let date3 = dateFormatter.dateFromString("02-06-2010") //var date1 = NSDate() dates.append(date3!) dates.append(date1!) dates.append(date2!) var maxDate = dates[0] for i in 0...dates.count-1 { if(maxDate.compare(dates[i]).rawValue == -1){ maxDate = dates[i] println(maxDate) } println(maxDate) } println(maxDate.description)
have a good day :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.