【问题标题】:(Swift) How unwrap the optional value properly? Firebase uid returning nil after authentication(Swift) 如何正确解开可选值? Firebase uid 在身份验证后返回 nil
【发布时间】:2017-06-24 16:46:27
【问题描述】:

我是 Swift 新手,在使用 Firebase UID 时遇到了问题。

  usersReference.child("users").observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
            print(snapshot)
            if snapshot.hasChild((FIRAuth.auth()?.currentUser!.uid)!)
            {
                print("This user already exist")
            //code

                }

致命错误:在展开可选值时意外发现 nil

请指教,如何正确解包?还是别的什么?

【问题讨论】:

  • (FIRAuth.auth()?.currentUser!.uid)! 如果您创建了新用户或登录了现有用户,则不会为零。

标签: swift firebase uid


【解决方案1】:

您在没有先检查它们是否为 nil 的情况下解开两个可能为 nil 的值

  1. FIRAuth.auth()?.currentUser!

currentUser 属性返回“当前登录的用户(或 null)。”

  1. (FIRAuth.auth()?.currentUser!.uid)!

要检查第一次或第二次展开是否导致致命错误:在展开可选值时意外发现 nil,请像这样重组 if 语句:

if FIRAuth.auth()?.currentUser == nil {
    print("no user logged in")
} else if FIRAuth.auth()?.currentUser!.uid == null {
    print("no user id value")
} else if snapshot.hasChild((FIRAuth.auth()?.currentUser!.uid)!) {
    print("This user already exist")
} else {
    // code to handle new user
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2018-04-08
    相关资源
    最近更新 更多