ios - 检查nil后意外发现nil

标签 ios swift firebase null

我正在尝试将 Firebase 用户名保存到 UserDefault。这是我所拥有的:

let databaseRef = FIRDatabase.database().reference()
databaseRef.child("Users").child((FIRAuth.auth()?.currentUser?.uid)!).observe(.value, with: { (snapshot) in
    print("log in 4")
    print(snapshot.value)
    if snapshot.value != nil {
        print("log in 4.1")
        UserDefaults.standard.set(snapshot.value!["username"], forKey: "username")//Crash probably occurs here
        print("log in 4.2")
    }

})

系统打印log in 4log in 4.1,但不是4.2。错误必须发生在两者之间的线上。我检查 snapshot.value 不是 nil,但它仍然打印 nil。我该如何解决这个问题?谢谢!

最佳答案

您当前只是检查 snapshot.value 是否包含 any 值,因此不是 nil。但这并不意味着 snapshot.value 包含值 "username"

如果初始化为空,则它也不是 nil。

因此,要检查这个特定的 key ,您必须添加对 key 本身的检查:

if let userValue = snapshot.value?["username"]

关于ios - 检查nil后意外发现nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38647826/

相关文章:

android - 您不能在尚未附加的 View 或 getActivity() 返回 null 的 fragment 上开始加载

ios - C/XCode : sh: ./child : No such file or directory. 命令在终端中运行,但不在 XCode 中运行

ios - 如何正确登录到 spotify?

swift - Collection View 单元格自动布局每个单元格的不同高度

firebase - 当我使用相同的现有数据执行操作时,Firestore 写入计数是否会增加?

javascript - 缺少应用程序配置值 : "projectId" even though I am passing it in

ios - 钛 ti.storekit 返回空产品

ios - CMSampleBuffer 在 Swift 3 中从纵向旋转到横向

compiler-errors - 限制表达式中的术语数?

uitableview - 无法在表@masterViewController中显示url