swift - 无法更改 if-else 中的变量,Swift
问题描述
我在我的 iOS 应用程序中使用 Firebase 并创建了一个函数,该函数从 Firestore 数据库返回一个值。问题是变量val在 if-else 构造后不会改变。
func getData(collection: String, doc: String, key: String) -> String {
var val = "Simple string"
var db: Firestore!
let settings = FirestoreSettings()
Firestore.firestore().settings = settings
db = Firestore.firestore()
let docRef = db.collection(collection).document(doc)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
val = (document.get(key) as! String)
print(val)
} else {
val = "ERROR"
print("Document does not exist")
}
}
return val
}
此函数必须从 Firebase 返回值(我可以通过print(val)看到它),但最后它返回初始值Simple string。
我想我应该使用闭包来捕获 if-else 构造中的值,但我不知道该怎么做。
解决方案
将您的代码分为 3 个部分,如下所示:
#1
docRef.getDocument { (document, error) in
#2
}
#3
不能保证,但执行顺序可能是 #1 -> #3 -> #2:
- 初始化并调用
getDocument
#1 - 返回
val
#Simple String
3 - 连接到服务器,获取文档,调用#2
所以返回值将是Simple string
。因为#2 将异步执行。
正确的方法是:
func getData(
collection: String,
doc: String,
key: String,
handler: @escaping (String) -> Void
) {
#1
docRef.getDocument { (document, error) in ...
if... else...
callback(result)
}
}
使用将像:
getData(collection: .., doc: .., key: ..) { val in
print(val)
}
推荐阅读
- c# - 缺少 using 指令
- vb.net - 通过串行接收完整的字符串
- intellij-idea - 在 IntelliJ 中创建许多单元测试?
- python - 根据数据框列的部分添加一列标准化值
- mysql - MySQL:在一个语句中混合 SET @variable 和 SELECT
- kibana - 如何在kibana中搜索破折号(-)?
- sql-server - 使用一个选择语句如何获得下表结果
- c# - 如何在 LinQ 的 IQueryable 查询中添加序列号?
- java - 定义要覆盖的方法
- powershell - 我需要如何更改我的代码以适应 HKEY_USERS 格式而不是 HKCU?