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

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

问题描述

我正在尝试设置一个在该闭包内的闭包外的变量,但最终没有设置.但是,我将变量设置为 的值正在打印到控制台.此外,在设置返回变量并自行打印之后,正确的值正在打印到控制台.当我返回变量时出现问题;它的值与初始化时的值保持一致.这是一些伪代码:

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

希望能帮到你

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

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