如何将nil作为字典<string,anyobject>的参数传递

时间:2016-07-11 18:50:19

标签: swift swift2

我有一个类型为Dictionary<String, AnyObject>的词典,我需要将参数传递为nil:

let params = [
            "number": nil,
            "description": nil,
            "lang" : "spa",
            "byFee": true,
            "plan" : data.Plan
            ] as Dictionary<String, AnyObject>

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

如果我这样做,我会收到错误:

enter image description here

所以我尝试将词典更改为Dictionary<String, AnyObject?>

但如果我这样做,则错误会出现在request.HTTBody:

enter image description here

  

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

A null value in JSON is equivalent to NSNull in ObjC/Swift:

let params : [String : AnyObject] = [
    "number": NSNull(),
    "description": NSNull(),
    "lang" : "spa",
    "byFee": true,
    "plan" : data.Plan,
]

答案 1 :(得分:0)

Try this,

let params = [
        "number": "",
        "description": "",
        "lang" : "spa",
        "byFee": true,
        "plan" : data.Plan
        ] as Dictionary<String, AnyObject>

    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])