swift - 如何从闭包中检索要在函数中返回的值?
问题描述
我有一个 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 服务器获取的值。
我该如何纠正这个问题?
解决方案
您要做的是在函数内部创建一个回调作为参数。
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)
}
}
}
推荐阅读
- machine-learning - 你应该在张量流中的超参数搜索期间设置随机种子数吗?
- dc.js - 在 dc-js geoChoropleth 图表的标题中使用完整的组记录
- python - neomodel 无法匹配记录
- c# - Unexpected '集合被修改;枚举操作可能无法执行。List 枚举的例外,尽管 List 没有被修改
- flutter - 是否可以在 Flutter 中启动 SizedBox 的二维数组(例如,我需要某种正方形)
- laravel - 当用户单击使用 laravel 的文章时,我正在尝试增加 DB 中的计数值
- node.js - 在 NPM 包中使用 require
- call - 如何在laravel中将刀片文件调用到另一个刀片文件?
- vba - VBA访问无效使用Null
- html - 我的指向其他 html 页面的 href 链接不起作用