Return 在 Swift 中使用 Firebase 的语句错误

Return Statement Error using Firebase in Swift

我创建了一个连接到 firebase 的函数,转到特定路径然后给我值。当我打印(snapshot.value)时,它给了我需要的值。当我调用该函数时,userProfile 为空。我需要 userProfile 到 return 快照字符串。

 func getUserData(uid: String) -> String{
   var _REF_USERNAME = FIRDatabase.database().reference().child("users").child(uid).child("profile").child("username")

     var userProfile = String()


    _REF_USERNAME.observe(.value, with: {(snapshot) in
        print("SNAP: \(snapshot.value)")
            userProfile = snapshot.value as! String

    })
    print(userProfile)
    return userProfile
}

Swift 3

您在 observe 的回调之外调用 userProfile,因此它将在 observe 函数异步完成之前执行。回调一开始很难理解,但大意是你的代码并不是从上到下依次运行,有部分代码是在后台线程中异步运行的。

要访问 userProfile,您必须像这样传入一个回调函数:

func observeUserProfile(completed: @escaping (_ userProfile: String?) -> ()) -> (FIRDatabaseReference, FIRDatabaseHandle) {

    let ref = _REF_USERNAME

    let handle = ref.observe(.value, with: {(snapshot) in
            if !snapshot.exists() { // First check if userProfile exists to be safe
                completed(nil)
                return
            }
            userProfile = snapshot.value as! String
            // Return userProfile here in the callback
            completed(userProfile)
    })
    // Good practice to return ref and handle to remove the handle later and save memory
    return ref, handle

然后你在传入回调函数时在外部调用此观察代码:

let ref, handle = observeUserProfile(completed: { (userProfile) in
     // Get access to userProfile here
     userProfile
}

完成此观察器后,通过执行以下操作停止观察以节省内存:

ref.removeObserver(withHandle: handle)