Search code examples
iosswiftnsdictionarynsobject

How to convert NSDictionary to NSObject in Swift?


I have a meta variable NSObject in a viewcontroller that I intend to be able to receive any kind of object from the parent viewcontroller that pushes it. I also have a type variable that will determine how I typecast and interpret this NSObject inside the viewcontroller.

The problem is when I tried to cast an NSDictionary into NSObject in the parent, Xcode warns that that type of typecasting will always fail.

Code that I have tried:

childVc.meta = ["title":"test"] as! NSObject; // warning: cast from '[String:String?]' to unrelated type 'NSObject' always fails.

let data = ["title":"test"];
childVc.meta = data as! NSObject; // warning: cast from '[String:String?]' to unrelated type 'NSObject' always fails.


let data = ["title":"test"];
childVc.meta = data as NSObject; // error: cannot convert value of type '[String:String?]' to type 'NSObject' in coercion.


let data = ["title":"test"] as! NSObject; // warning: cast from '[String:String?]' to unrelated type 'NSObject' always fails.
childVc.meta = data;

But the opposite typecasting always works:

let unwrappedMeta = self.meta as! NSDictionary;

Oh btw, I know that swift doesn't need semicolon at the end. It's just my habit from obj-c and swift looks like doesn't care about it, so don't let this semicolon distract us. :)


Solution

  • You have an optional value in dictionary, seems not to be NSDictionary.

      // warning: cast from '[String:String?]'
    

    Try to cast it as AnyObject