How to return value from close function in iOS / swift?

I am just starting to learn the development of iOS coming from the backend. I want to pass this function to userID and return the name, all the data coming from Firebase. My current attempt to break the name value from the close does not work, an empty string is returned. How can I organize the structuring of this code in order to return the 'name' variable.

    func getNameOfUser(uid: String) -> String {
    var name: String = ""
    FIRAuth.auth()?.signInAnonymouslyWithCompletion() { (user, error) in
        self.ref = FIRDatabase.database().reference()
        self.ref!.child("users").child(uid).child("name").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            name = snapshot.value! as! String
        }) { (error) in
            print(error.localizedDescription)
        }
    }
    return name
}
+4
source share
1 answer

This will not work. signInAnonymouslyWithCompletion()running in the background.

Asynchronously creates and becomes an anonymous user.

, getNameOfUser() , .

func getNameOfUser(uid: String) -> String 
{
  var name: String = ""
  FIRAuth.auth()?.signInAnonymouslyWithCompletion() 
  { (user, error) in
  // Executed somewhere in the future
  }
// Executed immeditaly.
return name
}

, , .

+2

All Articles