How to sort an array of strings representing month and year?

arrays, sorting, string, swift3

Solution

Why not simply

let formatter : DateFormatter = {
    let df = DateFormatter()
    df.locale = Locale(identifier: "en_US_POSIX")
    df.dateFormat = "MMMM yyyy"
    return df
}()

let arrayOfMonths = ["May 2017", "January 2018", "August 2016", "January 2015", "June 2017"]

let sortedArrayOfMonths = arrayOfMonths.sorted( by: { formatter.date(from: $0)! < formatter.date(from: $1)! })

Problem

I have an array of strings in my code which represents a series of months in years. Something like this: ``` let arrayOfMonths = ["May 2017", "January 2018", "August 2016", "January 2015", "June 2017"] ``` I'd like to sort it, by following the classic succession of months and years, so I'd like an output like this: ``` let sortedArrayOfMonths = ["January 2015", "August 2016", "May 2017", "June 2017", "January 2018"] ``` How can I do it in Swift 3? Thanks.

Original source