arraysswiftsortingnscountedset

Array Not Sorted Correctly


I want to sort my array by month and year. I successfully did that with the following code:

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"]

Now that I have my array sorted in the correct order I want to count how many of the same months I have. I successfully do that with the following code:

var counts = [Int]()
let countedSet = NSCountedSet(array: sortedArrayOfMonths)
for item in countedSet {
    counts.append(countedSet.count(for: item))
    print("\(item) : \(countedSet.count(for: item))")
}

The problem is that now my array is out of order. The following code prints:

 January 2015 : 1
 July 2018 : 1
 June 2017 : 1
 July 2019 : 1
 June 2018 : 2

How can I re-sort my array? I'm not sure why it's out of order. You can put the code in Playgrounds and test it out. Thanks


Solution

  • So after messing around with the code on playgrounds. I found a workable solution. First we sort the array:

    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)
    

    After the array is sorted we will loop through that array and add the date to a new array, dqw, only if that date does not previously exist in the new array. Then we add the number of times that date occurs to another array 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))
        }
    }
    

    Now we can loop the new dqw array we created and the counts array and print our results.

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

    Results:

    January 2015 : 1
    June 2017 : 1
    June 2018 : 2
    July 2018 : 1
    July 2019 : 1