我想按月和年对数组进行排序。我使用以下代码成功地做到了这一点:
let formatter : DateFormatter = {
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "MMMM yyyy"
return df
}()
let arrayOfMonths = ["June 2018", "July 2019", "June 2018", "July 2018", "January 2015", "June 2017"]
let sortedArrayOfMonths = arrayOfMonths.sorted( by: { formatter.date(from: $0)! < formatter.date(from: $1)! })
//prints ["January 2015", "June 2017", "June 2018", "June 2018", "July 2018", "July 2019"]
现在我已经按照正确的顺序对数组进行了排序,我想计算我有多少相同的月份。我使用以下代码成功地做到了这一点:
var counts = [Int]()
let countedSet = NSCountedSet(array: sortedArrayOfMonths)
for item in countedSet {
counts.append(countedSet.count(for: item))
print("\(item) : \(countedSet.count(for: item))")
}
问题是现在我的数组出现故障了。以下代码打印:
January 2015 : 1
July 2018 : 1
June 2017 : 1
July 2019 : 1
June 2018 : 2
如何重新排序我的数组?我不确定它为什么不正常。您可以将代码放入Playgrounds
并进行测试。谢谢