How do I convert swift Dictionary to NSDictionary

北慕城南 提交于 2019-11-30 03:00:29

问题


I'm trying to convert a [String : String] (a Swift Dictionary) to NSDictionary, for later use on a JSON library that produces a string

var parcelDict = ["trackingNumber" : parcel.number,
                  "dstCountry" : parcel.countryCode];

if (parcel.postalService != nil) 
{
    parcelDict["postalService"] = parcel.postalService;
}

var errorPtr: NSErrorPointer
let dict: NSDictionary = parcelDict
var data = NSJSONSerialization.dataWithJSONObject(dict, options:0, error: errorPtr) as NSData

return NSString(data: data, encoding: NSUTF8StringEncoding)

but let dict: NSDictionary = parcelDict does not work

let dict: NSDictionary = parcelDict as NSDictionary

var data = NSJSONSerialization.dataWithJSONObject(parcelDict as NSMutableDictionary, options:0, error: errorPtr) as NSData

All of these examples do not work. They produce the following errors:

What's the correct way of doing it?

Update:

Code that works

var parcelDict = ["trackingNumber" : parcel.number!,
                  "dstCountry" : parcel.countryCode!];

if (parcel.postalService != nil) {
    parcelDict["postalService"] = parcel.postalService;
}

var jsonError : NSError?
let dict = parcelDict as NSDictionary
var data = NSJSONSerialization.dataWithJSONObject(dict, options:nil, error: &jsonError)
return NSString(data: data!, encoding: NSUTF8StringEncoding)!

回答1:


You have to cast it like this:

let dict = parcelDict as NSDictionary

Otherwise the Swift Dictionary and NSDictionary are treated almost the same way when using it in methods for ex:

func test(dict: NSDictionary) {}

let dict = ["Test":1]
test(dict)

Will work completely fine.


After your update

If you change your Dictionary value type to non optional String then your error will go away.

[String:String?] change to -> [String:String]



回答2:


You can use this easy method

let dictSwift = ["key1": "value1", "key1": value2]

let dictNSMutable = NSMutableDictionary(dictionary: dictSwift)

Enjoy coding!




回答3:


Don't don't need to convert it to an NSDictionary. Just use:

var data = NSJSONSerialization.dataWithJSONObject(parcelDict, options:0, error: errorPtr) as NSData

It's mentioned in this post: Making a JSON object in Swift

Edit

From your screenshots I believe your problem lies in the value type in your parcelDict Dictionary. I can recreate the error with the following code:

let dict = [String: String?]()
let nsDict = dict as NSDictionary // [String: String?] is not convertible to NSDictionary

However, using a String instead of a String? as the value type removes the error.

Therefore, when populating parcelDict perhaps you should only add to it values which are not nil.



来源:https://stackoverflow.com/questions/29502878/how-do-i-convert-swift-dictionary-to-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!