快速关闭未设置变量 [英] Swift closure not setting variable

查看:63
本文介绍了快速关闭未设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在该闭包内的闭包外设置一个变量,但最终并没有设置好该变量。但是,我将变量设置为 的值正在打印到控制台。同样,在设置返回变量并自行打印之后,将正确的值打印到控制台。当我返回变量时会出现问题。它的值与初始化时的值相同。以下是一些伪代码:

I'm trying to set a variable that is outside a closure inside that closure, but it doesn't end up getting set in the end. However, the value that I'm setting the variable to is being printed to the console. Also, right after setting the return variable and printing it itself, the correct value is being printed to the console. The problem arises when I return the variable; its value stays the same as the value at initialization. Here is some psuedo-code:

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"
}()

这是不起作用的实际代码:

This is the actual code that isn't working:

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正在异步工作。

.observeSingleEvent is working async.

您可以执行以下操作:

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)
            }
        }
    })
}

然后,您可以在任何需要的地方使用它:

Then, you can use it everywhere you want:

getRetname(completion: { ret_name in 
    // ret_name - your data
})

希望有帮助

这篇关于快速关闭未设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆