swift - 为什么这个函数没有返回任何东西?

标签 swift

func RevisarConectividad() -> String
    {
        var Estado = ""
        let Referencia = Database.database().reference(withPath: ".info/connected")

        Referencia.observe(.value, with:
        { snapshot in
            if snapshot.value as? Bool ?? false
            {
                Estado = "Conectado"
            }
            else
            {
                Estado = "NoConectado"
            }
            print(Estado)
        })
        print("Estado:" + " " + Estado)
        return Estado


    }

我这样调用它:

let Estado = RevisarConectividad()

但出于某种原因,Estado 似乎从未接受过这两个字符串中的任何一个。不管怎样,我在闭包内打印了“Estado”,它正在工作,它正确地打印了它的值。

最佳答案

“observe”是一个异步函数,当您返回“estado”时,该值尚未设置。您可以传递回调,并在函数内调用它。

func RevisarConectividad(completion: @escaping (_ state:String) -> ())
{
    var Estado = ""
    let Referencia = Database.database().reference(withPath: ".info/connected")

    Referencia.observe(.value, with:
        { snapshot in
            if snapshot.value as? Bool ?? false
            {
                Estado = "Conectado"
            }
            else
            {
                Estado = "NoConectado"
            }
            completion(Estado)
    })
}

然后:

RevisarConectividad { (state) in
    print(state)
}

关于swift - 为什么这个函数没有返回任何东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52727139/

相关文章:

ios - SpriteKit - 在 Gamescene.sks 中创建 Sprite 并在另一个类中引用

ios - 将观察者添加到 UITextField 文本已更改

ios - 如何快速创建过滤器数组

swift - CryptoKit 上的 HMAC 更新

swift - 如何正确解决我的函数中的 EXC_BAD_ACCESS (code=EXC_i386_GPFLT) 错误

swift - “弱”可能只适用于类和类绑定(bind)协议(protocol)类型,而不是 'ContentView' 我缺少什么?

ios - 了解可选链接和可选解包选项

swift - 有没有办法与 FileManager 和 NSBundle 配合使用来获取/Applications 目录中支持给定类型文件的所有应用程序?

xcode - 数组的不可变值仅具有名为append的可变成员

Swift 3 FileManager.default(......).first 是什么意思?