0

I have an array of names of months. I need to create dictionary with key of type Int and value of type String. With the help of for loop I have to set value to be an element of month’s array and key to be an index. I’ve done that, but I need to sort dictionary. So I created sortWithKeys function, but it sort incorrect.

var month = ["January", "February", "March", "April", "May", "June", "July", "August" ,"September" ,"October", "November", "December"]

var monthDict: [Int:String] = [:]

    for j in 0..<12 {
        monthDict[j + 1] = month[j]
    }

func sortWithKeys(_ dict: [Int: String]) -> [Int: String] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [Int: String] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

print(sortWithKeys(monthDict))
koen
  • 5,383
  • 7
  • 50
  • 89
Danya
  • 13
  • 3
  • 5
    First of all a plain Dictionary is unordered so you can't have it sorted but more importantly why do you even need this when you already have a correctly sorted array? – Joakim Danielson Jan 10 '23 at 13:14
  • 1
    Beside the linked dupe, see also https://github.com/apple/swift-collections/blob/main/Documentation/OrderedDictionary.md (which is fairly new and not yet part of stdlib) – Rob Napier Jan 10 '23 at 14:51

0 Answers0