How to convert a Swift dictionary to NSDictionary

I am trying to convert [String : String] (Swift Dictionary) to NSDictionary , for later use in the JSON library that creates the 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 cause the following errors:

enter image description here

enter image description here

What is the right way to do this?

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)! 
+6
source share
3 answers

You should do it as follows:

 let dict = parcelDict as NSDictionary 

Otherwise, the words Swift and NSDictionary are processed almost the same when used in ex methods:

 func test(dict: NSDictionary) {} let dict = ["Test":1] test(dict) 

Will work completely fine.


After update

If you change the type of the dictionary value to an optional string, your error will disappear.

 [String:String?] change to -> [String:String] 
+9
source

You can use this simple method.

 let dictSwift = ["key1": "value1", "key1": value2] let dictNSMutable = NSMutableDictionary(dictionary: dictSwift) 

Enjoy the coding!

+1
source

No need to convert it to NSDictionary . Just use:

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

This post mentions: Creating a JSON object in Swift

Edit

From your screenshots, I believe your problem is the type of values ​​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 String instead of String? because the type of the value removes the error.

Therefore, when filling out parcelDict perhaps you should add only values ​​that are not nil .

0
source

Source: https://habr.com/ru/post/984821/


All Articles