0

我想按月和年对数组进行排序。我使用以下代码成功地做到了这一点:

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并进行测试。谢谢

4

1 回答 1

0

所以在操场上弄乱了代码之后。我找到了一个可行的解决方案。首先我们对数组进行排序:

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)! })
print(sortedArrayOfMonths)

数组排序后,我们将遍历该数组并将日期添加到新数组中dqw,前提是该日期以前不存在于新数组中。然后我们将日期出现的次数添加到另一个数组中counts

var counts = [Int]()
var dqw = [String]()
let countedSet = NSCountedSet(array: sortedArrayOfMonths)
var i = 0
for item in sortedArrayOfMonths {
    if dqw.contains(item) {
        print("already exist")
    } else {
        dqw.append(item)
        counts.append(countedSet.count(for: item))
    }
}

现在我们可以循环dqw我们创建的新数组和counts数组并打印我们的结果。

while i < dqw.count {
   print("\(dqw[i]) : \(counts[i])")
   i += 1
}

结果:

January 2015 : 1
June 2017 : 1
June 2018 : 2
July 2018 : 1
July 2019 : 1
于 2018-07-17T20:56:51.787 回答