首页 > 解决方案 > 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.findself.foo2print(self.bar)truefalse

如何更改' 的值,以便更改也将在' 范围self.bar之外生效?collection.find

标签: swiftmongodbscoperealm

解决方案


正如@Jay 评论的那样:

闭包是异步的,闭包之后的代码将(可能)在闭包中的代码之前执行。因此,该代码将在值设置为 true 之前打印 false。代码比互联网快,所以数据只在闭包中有效。

这就是为什么在我的情况下,闭包的print(self.bar)外部是在闭包之前执行的collection.find。因此它的结果是false而不是true.


推荐阅读