1

I've already searched and really, asking a question on here was my last resort... honestly, but feel free to downvote the heck out of me since "I had to ask"...! now down to business...

I have a dictionary with two levels "dict > keys", that's it! but for whatever reason that I can't seem to get the "three" value out. Where did I go wrong here?

print(mainDict)

/*
 ["keys": {
     one = "one...";
     two = 2;
     three = "three"; // need this one!
 }]
*/

let sub = mainDict["keys"]
print(sub as Any)

/*
 Optional({
     one = "one...";
     two = 2;
     three = "three";
 })
*/

Great! so far so good... but then:

let keyThree = mainDict["three"]
print(keyThree as Any)
// nil

let keyThree = sub["three"]
// Type 'NSObject?' has no subscript members

WTH? ... TRIED:

Community
  • 1
  • 1
ctfd
  • 338
  • 3
  • 14
  • please share the initialization of the dictionary – Amr Eladawy Feb 03 '17 at 08:02
  • @AmrElAdawy: `func makeThisPossible(mainDict: [String : NSObject])` – ctfd Feb 03 '17 at 08:03
  • share the code where you set the values initially – Russell Feb 03 '17 at 08:12
  • @Russell: You mean `let mainDict = (userInfo as? [String: NSObject])!` ?, the function that is called from is `optional func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any])` – ctfd Feb 03 '17 at 08:19

1 Answers1

2

The declaration of mainDict in the function signature has to be [String :[String:Any]]. Or you can declare it as [String:Any] and then, you need to cast the sub as [String:Any]

So the function should be

func makeItPossible(mainDict : [String:Any]){
   if let sub= mainDict["keys"] as [String:Any], let keyThree = sub["three"]{
        print(keyThree)
}

Updated to use conditional binding.

Amr Eladawy
  • 4,193
  • 7
  • 34
  • 52