问题
In some case i have to post null values to server either as a default value or as a parameter's value.I tried many ways but it didnt work.I'm using Alamofire for posting a request.Please help.
Method-1
var empty : String = ""
let parameters = ["User-Id":userId,"search_cat": formattedArray ?? empty,"date1":ab ?? empty,"date2" : bc ?? empty,"docname" : empty
] as! [String : String]
Method-2
let parameters = ["User-Id":userId,"search_cat": formattedArray ?? "","date1":ab ?? "","date2" : bc ?? "","docname" : ""
] as! [String : String]
Method-3
var nullvalue : String = ""
if formattedArray == nil
{
formattedArray = ""
print(formattedArray)
}
if ab == nil
{
ab = ""
print(ab)
}
if bc == nil
{
bc = ""
print(bc)
}
if nullvalue == nil
{
nullvalue = ""
}
parameters = ["User-Id":userId,"search_cat": formattedArray,"date1":ab ,"date2" : bc ,"docname" : nullvalue ]
as! [String : String]
Method - 4 According to answer i changed parameterlist dictionary to [String:AnyObject] but still it's not working.And giving me the error.
var ab:String?
var bc : String?
var formattedArray: String?
parameters = ["User-Id":userId ,"search_cat": formattedArray ?? NSNull() ,
"date1":ab ?? NSNull() ,"date2" : bc ?? NSNull(),
"docname" : NSNull()] as! [String : AnyObject]
Method-4 giving me Error while trying to set formattedArray ?? NSNull() : Cannot convert value of type 'NSNull' to expected argument type 'String' with rest of the parameters its working fine.Please help.
回答1:
UPDATED : is this that you want?
class RequestParameter : NSObject{
var formattedArray : String!
var date1 : String!
var date2 : String!
var docName : String!
var userId : String! // or whatever if hardCoded
func param() -> NSDictionary{
var param : [String : String] = [:]
param["User-Id"] = userId
param["search_cat"] = formattedArray
param["date1"] = date1
param["date2"] = date2
param["docname"] = docName
return param as! NSDictionary
}
}
You can call these parameters where ever required. like
var reqParam = RequestParameter()
reqParam.param()
I am really unaware of your Request parameter type. For eg. should it look like date1 = nil or something else. This is all I could answer you. If wrong maybe someone might ans better.
Good Luck!!
回答2:
I actually had the same issue a couple of days ago and solved it using NSNull().
When converting my class I want to send the videoUrl property regardless of it containing a value, so that the backend can update it in the DB.
dict["videoUrl"] = videoUrl ?? NSNull()
This will set the key "videoUrl" with the value of the property videoUrl, or if nil, an instance of NSNull().
Express.js then reads this as undefined and inserts a null value to the database.
EDIT: I saw one of your comments below. When using a Dictionary of type [String:String], you will never be able to pass a nil value.
来源:https://stackoverflow.com/questions/48111242/how-we-can-pass-default-null-value-in-parameter-list-of-dictionary-stringstrin