有些情況下在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"}