Swift Firebase函数返回 [英] Swift Firebase Function Return

查看:90
本文介绍了Swift Firebase函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在返回函数中使用Firebase值.对我来说,这似乎是一个持续存在的问题.我已经写了一个基本的例子来说明我的问题.我该怎么做呢?

I'm having a hard time with Firebase values in return functions. This seems to be an ongoing problem for me. I have written up a basic example of my issue. How do I go about doing this?

func getChartIndexValues(completion:@escaping (Double) -> ()) {

    //Firebase Initialization
    var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()

    ref.child("general_room_index").observeSingleEvent(of: .value, with: {(snapshot) in

        let snapDict = snapshot.value as? NSDictionary
        var zero = snapDict?["0"] as! Double

        completion(zero)
        })

}


   returnFunction() -> (Double) {

      getChartIndexValues() { (zero) -> () in

            let testValue = zero
        }


     return //THis is my problem
}

推荐答案

您已经暗示了您的问题,但没有明确指出.问题是您不能将异步函数的结果作为函数结果返回.您需要传递一个在函数完成时运行的完成处理程序,该代码是可以访问结果的代码.

You've hinted at your problem, but not stated it explicitly. The deal is that you can't return the result of an async function as a function result. You need to pass in a completion handler that runs when the function finishes, and that code is the code that has access to the result.

returnFunction() -> (Double) {

  getChartIndexValues() { (zero) -> () in

    //Your code to process the results belongs here
    self.someInstanceVar = zero
    someLabel.text = "Your result is \(zero)"
    }

}
//You CAN'T put your code to process results here.

这篇关于Swift Firebase函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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