John John - 25 days ago 7
iOS Question

How to assign null value in dictionary?

I need to send to server parameters like this:

"searchConditions": {
"firstNameLastName": "My Name",
"email": null,
}


I'm trying to send like this:

let searchParameters: [String: AnyObject] = [
"firstNameLastName": self.byNameField.text!,
"email": ""
}


but server sees that
"email": ""
as
email=


When I try to set
"email": nil
it gives me an error:

Nil is not compatible with expected dictionary value type 'AnyObject'


How can I send "null" value to my server?

Answer

John,

You can use NSNull() to insert null in dictionary,

like

let test : [String : AnyObject] = ["test" : NSNull()]

When you print the value of test key you will get

po test["test"]
▿ Optional<AnyObject>
  - Some : <null>