Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

ios - How do I convert swift Dictionary to NSDictionary

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:

enter image description here

enter image description here

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)!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...