Hem Poudyal Hem Poudyal - 10 months ago 67
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


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.