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/