(Swift)如何正确打开可选值?验证后Firebase uid返回nil

时间:2022-09-11 18:30:10

I'm new to Swift, have a trouble with Firebase UID.

我是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

                }

fatal error: unexpectedly found nil while unwrapping an Optional value

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

Please advise, how unwrap it properly? Or maybe something else?

请指教,如何妥善打开它?或者别的什么?

1 个解决方案

#1


1  

You are unwrapping two potentially nil values without first checking to see if they are nil

您正在解开两个潜在的nil值,而不先检查它们是否为零

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

The currentUser property returns "The currently signed-in user (or null)."

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

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

To check if the first or second unwrapping is causing the fatal error: unexpectedly found nil while unwrapping an Optional value, restructure your if statement like so:

要检查第一次或第二次展开是否导致致命错误:在展开Optional值时意外发现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
}

#1


1  

You are unwrapping two potentially nil values without first checking to see if they are nil

您正在解开两个潜在的nil值,而不先检查它们是否为零

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

The currentUser property returns "The currently signed-in user (or null)."

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

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

To check if the first or second unwrapping is causing the fatal error: unexpectedly found nil while unwrapping an Optional value, restructure your if statement like so:

要检查第一次或第二次展开是否导致致命错误:在展开Optional值时意外发现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
}