Chen Li Yong
Chen Li Yong

Reputation: 6107

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

Upvotes: 1

Views: 2985

Answers (2)

Igoretto
Igoretto

Reputation: 117

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

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

Try to cast it as AnyObject

Upvotes: 1

Mr. Bond
Mr. Bond

Reputation: 427

Please try to use like this:

var traitsDic : NSDictionary! = ["title":"test"]
var traits = traitsDic as Dictionary<String, AnyObject>

Upvotes: 0

Related Questions