swift - Swift + Realm:如何从 collection.find 的范围内更改外部变量
问题描述
按照本教程,我编写了以下类:
import RealmSwift
import Darwin
import SwiftUI
let app = App(id: "my-app-id")
class AccessManager: Object {
@objc dynamic var isInTime: Bool = false
func foo2() -> Bool {
return true
}
func foo1() {
app.login(credentials: Credentials.anonymous) { (result) in
DispatchQueue.main.async {
switch result {
case .failure(let error):
print("Login failed: \(error)")
case .success(let user):
print("Login as \(user) succeeded!")
let client = app.currentUser!.mongoClient("mongodb-atlas")
let database = client.database(named: "my-database")
let collection = database.collection(withName: "my-collection")
let identity = "my-identity"
collection.find(filter: ["_partition": AnyBSON(identity)], { (result) in
switch result {
case .failure(let error):
print("Call to MongoDB failed: \(error.localizedDescription)")
case .success(let documents):
self.bar = self.foo2()
print(self.bar) // prints true
}
})
print(self.bar) // prints false
}
}
}
}
}
当我更改' 范围self.bar
内的值(使用函数)时,它的值不会在该范围之外更改 - 即在第一个-正在打印,但在第二个 -被打印。collection.find
self.foo2
print(self.bar)
true
false
如何更改' 的值,以便更改也将在' 范围self.bar
之外生效?collection.find
解决方案
正如@Jay 评论的那样:
闭包是异步的,闭包之后的代码将(可能)在闭包中的代码之前执行。因此,该代码将在值设置为 true 之前打印 false。代码比互联网快,所以数据只在闭包中有效。
这就是为什么在我的情况下,闭包的print(self.bar)
外部是在闭包之前执行的collection.find
。因此它的结果是false
而不是true
.
推荐阅读
- windows - 我们如何构建一个 windows / WCF 服务来启动 OSCOVA Bot 的 WEB API 通道
- c# - 在 C# 中使用文件路径可视化文件字典的最佳实践
- angular - 是否可以将 angular7 组件或服务中的数据传递给 index.html 文件?
- listview - Xamarin.forms - ListView 和键盘之间的故障行为
- excel - 从 Google 表格脚本中解析 Excel 文件中的数据
- kubernetes - 为什么这个 Manifest 创建的 Pod 可以在不指定 Nodeselector 的情况下部署到 GPU Worker
- c# - 使用 ASP.NET 核心 MVC/Razor 站点和 WebAPI 进行授权
- node.js - Express 无法在 NodeJS 应用程序中使用 Typescript
- reactjs - TSX:阅读子孙的道具
- scala - 将sbt项目移动到新机器时如何避免重新下载sbt依赖包