ios - How to get the latest date from array in Swift -
i have array of dates. need find latest one. can show me example?
you can make nsdate conform comparable, shown here
given this, can use maxelement find maximum (i.e. 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 empty arrays may want guard isempty:
let maxdate = dates.isempty ? nil : optional(maxelement(dates)) or, if don’t want go extension route:
if let fst = dates.first { let maxdate = dropfirst(dates).reduce(fst) { $0.laterdate($1) } } or, return optional:
let maxdate = dates.reduce(nil) { (lhs: nsdate?, rhs: nsdate?)->nsdate? in lhs.flatmap({rhs?.laterdate($0)}) ?? rhs }
Comments
Post a Comment