首页 > 解决方案 > 无法更改 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 构造中的值,但我不知道该怎么做。

标签: swiftasynchronous

解决方案


将您的代码分为 3 个部分,如下所示:

#1
docRef.getDocument { (document, error) in
    #2
}
#3

不能保证,但执行顺序可能是 #1 -> #3 -> #2:

  • 初始化并调用getDocument#1
  • 返回val# Simple String3
  • 连接到服务器,获取文档,调用#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)
}

推荐阅读