【问题标题】:Swift Firebase Function ReturnSwift Firebase 函数返回
【发布时间】:2017-08-11 04:36:55
【问题描述】:

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

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
}

【问题讨论】:

    标签: ios swift firebase swift3 firebase-realtime-database


    【解决方案1】:

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

    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.
    

    【讨论】:

    • 那么你的意思是我不能绕过块在函数中返回一个值?我必须将它分配给一个标签或任何我想分配给它的东西?
    猜你喜欢
    • 1970-01-01
    • 2020-01-20
    • 2019-02-28
    • 2020-09-26
    • 2020-04-07
    • 2019-07-23
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多