小胖說swift06--------如何給Swift字典Dictionary增加空值

來源:互聯網
上載者:User
有些情況下在Swift中想讓Dictionary某個Key為空白值,比如在與伺服器互動時,有些參數無論有沒有值必須要求傳.但如果給字典的key賦值為nil,字典則會移除這個索引值對,如下:var dict1=Dictionary<String,AnyObject>()dict1["name"]="Jack"dict1["age"]=16dict1["nickname"]=nilprintln(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"]=16dict2["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"}
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.