如何给Swift字典Dictionary增加空值

如何给Swift字典Dictionary增加空值,第1张

有些情况下在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, options: NSJSONWritingOptions.allZeros, error: nil)!

let jsonString2 = NSString(data: jsonData2, encoding: NSUTF8StringEncoding)!

println(jsonString2) //{"age":16,"nickname":null,"name":"Jack"}

String seatname="set"+i+""+j

Seat seat

seat= new Seat(Seatsname, "green", 0)

seats.Add(seat.SeatName, seat)

改成 String seatname="set"+i+""+j

seats.Add(SeatName, new Seat(Seatname, "green", 0))

对啦,seat= new Seat(Seatsname, "green", 0)中Seatsname应该是笔误吧,我修改为Seatname


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/7907473.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-11
下一篇 2023-04-11

发表评论

登录后才能评论

评论列表(0条)

保存