Search code examples
iosstringswiftnullnsnull

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] =
            [
                "facebookId":self.fbResponse.fbID!,
                "fbToken":"randomToken",
                "email" : self.fbResponse.email!,
                "dateOfBirth": self.fbResponse.dob,
                "gender" : self.fbResponse.gender!,
                "info": self.fbResponse.aboutMe!,
                "fullName":self.fbResponse.fullName!,
                "profileImageUrl":self.fbResponse.pictureURL!
                "location": location
        ]

Solution

  • 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.