Hem Poudyal Hem Poudyal - 1 year ago 103
Swift Question

Set NSNull() if the string is nil

When a user does facebook login in my app, some of the expected value such as dateOfBirth, email can be nil. I want to set the value of self.fbResponse.email to NSNull(), if it is nil. So that I can post the parameters to server.

let parameter:[String:AnyObject] =
"email" : self.fbResponse.email!,
"dateOfBirth": self.fbResponse.dob,
"gender" : self.fbResponse.gender!,
"info": self.fbResponse.aboutMe!,
"location": location

Answer Source

You can use the ?? operator for that:

"email" : self.fbResponse.email ?? NSNull()

It assigns the unwrapped value of self.fbResponse.email if that is not nil, and assigns NSNull() otherwise.

The operator "short circuits", which means the right-hand side is not evaluated unless it really needs to because the left-hand side is nil.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download