-1

I am trying to initialise a Dictionary with Objects(Array) and respective keys. I am getting crash which says [NSDictionary initWithObjects:forKeys:]: count of objects (12) differs from count of keys (1)" . Not sure what I am missing here. Can someone help on this?

Below is my code.

 let df = DateFormatter()
        var months = [Any]()

        for monthIndex in 1...12 {
            months.append(df.monthSymbols[monthIndex - 1])
        }

        let monthDictionay = NSDictionary.init(objects: months, forKeys: ["values" as NSCopying]) 

It's crashing in the last line of code.

Below is what I want to achieve

My monthDictionary should have

values =     (
        January,
        February,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    );
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
AK1188
  • 17
  • 6

1 Answers1

1

You are using an NSDictionary (not Swift's Dictionary) method which takes an array of objects and a matching array of keys - note the plurals! You have one key whose matching value is an array. Just use a Swift dictionary literal:

let monthDictionary = [ "values" : months ]

Note: You will want to use var rather than let if you intend to add more keys & values.

CRD
  • 52,522
  • 5
  • 70
  • 86