小编典典

如何将Swift字典转换为NSDictionary

swift

我正在尝试将[String : String](Swift字典)转换为NSDictionary,以供以后在产生字符串的JSON库上使用

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)

let dict: NSDictionary = parcelDict不起作用

let dict: NSDictionary = parcelDict as NSDictionary

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

所有这些示例都不起作用。它们产生以下错误:

在此处输入图片说明

在此处输入图片说明

正确的做法是什么?

更新:

有效的代码

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)!

阅读 1316

收藏
2020-07-07

共1个答案

小编典典

您必须像这样强制转换:

let dict = parcelDict as NSDictionary

否则,在ex的方法中使用Swift字典和NSDictionary时,其处理方式几乎相同:

func test(dict: NSDictionary) {}

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

将完全正常工作。


更新后

如果将Dictionary值类型更改为非可选的String,则错误将消失。

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