首页 > 解决方案 > 如何从闭包中检索要在函数中返回的值?

问题描述

我有一个 fetch 调用应该返回一个字符串,这就是它的外观:

func fetchCallTwo() -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("path").document("subDoc")

    var returnableString: String = "DEFAULT VALUE"

    docRef.getDocument { (theDocument, error) in
        if let document = theDocument, document.exists {
            let field = document.get("field")

            if let field = field {
                print(field)

                returnableString = "\(field)"
            }
        }
    }

    print(returnableString)
    return returnableString
   }

但是,这总是返回“默认值”而不是我希望它返回的值,即从我的 firebase 服务器获取的值。

我该如何纠正这个问题?

标签: swiftreturnclosures

解决方案


您要做的是在函数内部创建一个回调作为参数。

func runFetch() {
    fetchCallTwo { (value) in
        // Do something
    }
}

func fetchCallTwo(callback: @escaping ((String) -> ())) {
 let db = Firestore.firestore()
 let docRef = db.collection("path").document("subDoc")

 var returnableString: String = "DEFAULT VALUE"

 docRef.getDocument { (theDocument, error) in
     if let document = theDocument, document.exists {
         let field = document.get("field")

         if let field = field {
             print(field)
            returnableString = field
         }
         callback(field)
     }
 }
}

推荐阅读