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))