John John - 1 year ago 82
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": ""

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 Source


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


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

When you print the value of test key you will get

po test["test"]
▿ Optional<AnyObject>
  - Some : <null>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download