How to add nil value to Swift Dictionary?

前端 未结 9 487
春和景丽
春和景丽 2021-01-31 01:20

I have made a request to my server in my app. And posted data something like this.Server side is waiting for all parameters even they are nil. But i couldn\'t add nil values to

9条回答
  •  悲哀的现实
    2021-01-31 02:00

    As documented in here, setting nil for a key in dictionary means removing the element itself.

    If you want null when converting to JSON for example, you can use NSNull()

    var postDict = Dictionary()
    postDict["pass"]=123
    postDict["name"]="ali"
    postDict["surname"]=NSNull()
    
    let jsonData = NSJSONSerialization.dataWithJSONObject(postDict, options: NSJSONWritingOptions.allZeros, error: nil)!
    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
    // -> {"pass":123,"surname":null,"name":"ali"}
    

提交回复
热议问题