ios - Swift Firebase 函数返回

标签 ios swift firebase swift3 firebase-realtime-database

我很难在返回函数中使用 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
}

最佳答案

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

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.

关于ios - Swift Firebase 函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894472/

相关文章:

iphone - UITabBarController,有什么可能的方法可以通过水平滑动移动下一个 View Controller?

ios - 另一个 "could not dequeue a view of kind: UICollectionElementKindCell with identifier song"

javascript - Firestore OrderBy 和Where 冲突

java - 如何将检索到的数据从 firebase 保存到 android 中的字符串变量?

firebase - 与写入 Firebase 实时数据库相关的连接成本是否取决于写入的数据量?

android - iOS和Android平台添加联系人时是否可以收到通知?

ios - Firebase/Swift 2 - 如何获取经过身份验证的用户密码和电子邮件

ios - 在 XMPP 中以后台模式工作

swift - Xcode/Swift 中的颜色和主题

ios - 如何创建像这样的 Onboarding/WalkThrough/App-intro swift 3