ios - 如果字符串为 nil,则设置 NSNull()

标签 ios string swift null nsnull

当用户在我的应用程序中登录 facebook 时,某些预期值(例如出生日期、电子邮件)可能为零。我想将 self.fbResponse.email 的值设置为 NSNull(),如果它为 nil。这样我就可以将参数发布到服务器。

        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
        ]

最佳答案

您可以为此使用 ?? 运算符:

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

如果 self.fbResponse.email 不是 nil,它会分配未包装的值,否则会分配 NSNull()

运算符“短路”,这意味着右侧被评估,除非确实需要,因为左侧是nil

关于ios - 如果字符串为 nil,则设置 NSNull(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965181/

相关文章:

ios - UIImageView 不更新图像

swift - SpriteKit 和 Swift 中的 SKPhysicsJoint 已修复

ios - 将 JSON 数据绑定(bind)到 TableView 和 CollectionView

ios - 为 iOS React-Native 项目设置 Fbsdk 框架

ios - 如何从具有多个条件的数组中删除重复项?

regex - 非确定性有限自动机 (NFA) 校正

ios - 无法更改 Apple Watch 通知中的窗框标题

ios - 无限奥特莱斯

java - `+=` 运算符是否总是创建一个新的字符串对象?

c - C语言打印字符串问题