ctfd
ctfd

Reputation: 348

Type 'NSObject?' has no subscript members

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:

Upvotes: 1

Views: 1302

Answers (1)

Amr Eladawy
Amr Eladawy

Reputation: 4358

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.

Upvotes: 2

Related Questions