有些情况下在Swift中想让Dictionary某个Key为空值,比如在与服务器交互时,有些参数无论有没有值必须要求传.但如果给字典的key赋值为nil,字典则会移除这个键值对,如下:
var dict1=Dictionary<String,AnyObject>()
dict1["name"]="Jack"
dict1["age"]=16
dict1["nickname"]=nil
println(dict1) //"[age: 16,name: Jack]"
let jsonData1 = NSJSONSerialization.dataWithJSONObject(dict1,options: NSJSONWritingOptions.allZeros,error: nil)!
let jsonString1 = NSString(data: jsonData1,encoding: NSUTF8StringEncoding)!
println(jsonString1) //"{"age":16,"name":"Jack"}"
如果像要字典的值为NULL,可以使用NSNULL,这样就可以达到像要的效果了:
var dict2=Dictionary<String,AnyObject>()
dict2["name"]="Jack"
dict2["age"]=16
dict2["nickname"]=NSNull()
println(dict2) //[age: 16,nickname: <null>,name: Jack]
let jsonData2 = NSJSONSerialization.dataWithJSONObject(dict2,error: nil)!
let jsonString2 = NSString(data: jsonData2,encoding: NSUTF8StringEncoding)!
println(jsonString2) //{"age":16,"nickname":null,"name":"Jack"}
原文链接:https://www.f2er.com/swift/323135.html