我试图设置一个变量,该变量位于该闭包内部的闭包外部,但最终不会被设置。然而,我设置变量的值 是 正在打印到控制台。同样,在设置返回变量并自行打印之后,将正确的值打印到控制台。当我返回变量时就会出现问题。其值与初始化时的值相同。这是一些伪代码:
let str: String = { var ret: String = "default value" functionWithClosure(with: (some_name) in { if let name = some_name { ret = name print(name) // prints successfully print(ret_name) // also prints successfully } }) return ret // returns "default value" }()
这是不起作用的实际代码:
let name: String = { var ret_name = "default value" if let uid = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { if let name = dictionary["name"] as? String { ret_name = name print(ret_name) } } }) } return ret_name }()
.observeSingleEvent正在异步工作。
您可以执行以下操作:
func getRetname(completion: @escaping(_ retName: String) -> Void) { if let uid = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { if let name = dictionary["name"] as? String { ret_name = name print(ret_name) completion(ret_name) } } }) }
然后,您可以在任何需要的地方使用它:
getRetname(completion: { ret_name in // ret_name - your data })
希望能帮助到你