Chubby says swift06--------How to add a null value to the Swift dictionary dictionary

Source: Internet
Author: User
In some cases, in swift, you want a dictionary key to be null, such as when interacting with the server, some parameters must be required to be transmitted regardless of value. However, if you assign nil to the key of the dictionary, the dictionary will remove the key value pair as follows: 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": +, "name": "Jack"} "if the value of the dictionary is null, you can use nsnull so you can achieve the desired effect: 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": +, "nickname": null, "name": "Jack"}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.