I need to sort a certain array with dates. Dates are stored in an array as strings.

func dateForm() -> String{ let formatterDate = DateFormatter() formatterDate.dateFormat = "dd/MM/yyyy" let someThing = Date() let result = formatterDate.string(from: someThing) return result } var date = dateForm() var array = ["29/01/2019", "03/10/2019", "31/01/2019", "29/01/2016", "01/01/2020"] array.sort() 

.sort () returns this:

 ["01/01/2020", "03/10/2019", "29/01/2016", "29/01/2019", "31/01/2019"] 

    1 answer 1

    as an option through date casting

     var array = ["29/01/2019", "03/10/2019", "31/01/2019", "29/01/2016", "01/01/2020"] func compareDates(_ first: String, _ second: String) -> Bool { let formatterDate = DateFormatter() formatterDate.dateFormat = "dd/MM/yyyy" return formatterDate.date(from: first)! < formatterDate.date(from: second)! } array.sort { compareDates($0, $1) } // ["29/01/2016", "29/01/2019", "31/01/2019", "03/10/2019", "01/01/2020"] 

    or

     var array = ["29/01/2019", "03/10/2019", "31/01/2019", "29/01/2016", "01/01/2020"] array.sort { let formatterDate = DateFormatter() formatterDate.dateFormat = "dd/MM/yyyy" return formatterDate.date(from: $0)! < formatterDate.date(from: $1)! } // ["29/01/2016", "29/01/2019", "31/01/2019", "03/10/2019", "01/01/2020"] 
    • It is worth remembering that creating a DateFormatter instance is a very expensive operation. For best performance, it’s worth creating it once, and when sorting, use the same instance each time - Dmitry Serov
    • @DmitrySerov totally agree, hastily done) - Andrey Iskamov February