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

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -