数组未正确排序

时间:2018-07-17 18:03:59

标签: arrays swift sorting nscountedset

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

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

1 个答案:

答案 0 :(得分: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