如何对表示月份和年份的字符串数组进行排序?

时间:2017-05-13 12:57:35

标签: arrays string sorting swift3

我的代码中有一个字符串数组,代表了几年的一系列数字。像这样:

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

我想按照几个月和几年的经典继承来排序,所以我想要这样的输出:

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

如何在Swift 3中执行此操作?感谢。

3 个答案:

答案 0 :(得分:4)

为什么不简单

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)! })

答案 1 :(得分:0)

我搜索了一下,我在Swift 3中找到了方法“.sorted()”,所以我构建了我的工作解决方案。我发布以防有人需要:

let monthForNumber = ["January":1, "February":2, "March":3, "April":4, "May":5, "June":6, "July":7, "August":8, "September":9, "October":10, "November":11, "December":12]

为了简洁起见,我创建了结构“Month”,使用“name”属性和“year”属性,我将使用对象月:

let month_1 = Month.init(name: "May", year: 2016)
let month_2 = Month.init(name: "April", year: 2010)
let month_3 = Month.init(name: "April", year: 2009)
let month_4 = Month.init(name: "January", year: 2026)
let month_5 = Month.init(name: "June", year: 2016)

let unsortedMonthsArray = [Month]()
unsortedMonthsArray.append(month_1)
unsortedMonthsArray.append(month_2)
unsortedMonthsArray.append(month_3)
unsortedMonthsArray.append(month_4)
unsortedMonthsArray.append(month_5)

let sortedArrayOfMonths = self.unsortedMonthsArray?.sorted(by: { (month1, month2) -> Bool in
        if self.monthForNumber[month1.name!] != self.monthForNumber[month2.name!] {
            if month1.year != month2.year {
                return month1.year < month2.year
            } else {
                return self.monthForNumber[month1.name!]! < self.monthForNumber[month2.name!]!
            }
        } else {
            if month1.year != month2.year {
                return month1.year < month2.year
            } else {
                return self.monthForNumber[month1.name!]! < self.monthForNumber[month2.name!]!
            }
        }
    })

此解决方案将提供一个已排序的Months数组,可以轻松转换为字符串数组(“monthName_monthYear”)。

答案 2 :(得分:0)

您也可以这样做:

let sortedMonths  = arrayOfMonths.map{($0,$0.components(separatedBy:" "))}
                    .map{($0,$1[1]+"\(Calendar.current.monthSymbols.index(of: $1[0])!+10)")}
                    .sorted{$0.1<$1.1}
                    .map{$0.0}