【问题标题】:SwiftUI Firebase Firestore Query FunctionSwiftUI Firebase Firestore 查询函数
【发布时间】:2020-01-09 18:54:47
【问题描述】:

我有一组从 Google Firestore “[428024, 4298212]”返回的 SKU 编号。

我已经编写了一个函数,将 SKU 的数组分配给一个变量,但我不知道如何从函数中返回该变量。

let db = Firestore.firestore()

func getItems() -> [Int]   {
    let userID = Auth.auth().currentUser?.uid ?? "nil"

    if (session.session != nil) {
        self.data.removeAll()
        db.collection("users").document(userID).getDocument { (document, error) in
            if let document = document, document.exists {
                 let itemID = document.get("items") as! Array<Int>
               print(itemID as Any)
               // Prints "[428024, 4298212]"
                return itemID
                } else {
                    print("Document does not exist")
                    }
                }
        }      
}

我收到错误“在 void 函数中出现意外的非 void 返回值,但我可以看到 SKU 的数组在运行“print(itemID as Any)”行时被返回。

我写的函数有什么错误吗?

【问题讨论】:

  • 快速说如果会话为零或文档不存在什么会返回你的函数?

标签: google-cloud-firestore swiftui


【解决方案1】:

通过 Firestore 查询文档是使用完成处理程序编写的,并且尝试从该处理程序中将任何值返回到您的原始函数将产生此错误。相反,您需要调整您的原始函数 getItems() 以解决此问题:

let db = Firestore.firestore()
@State private var itemIDs: [Int] = []

func getItems(completion: @escaping (_ itemIDs: [Int]?) -> ()) {

    let userID = Auth.auth().currentUser?.uid ?? "nil"

    if (session.session != nil) {
        self.data.removeAll()
        db.collection("users").document(userID).getDocument { (document, error) in
            if let document = document, document.exists {
                 let itemIDs = document.get("items") as! Array<Int>
                 completion(itemIDs) // call completion handler to return value
            } else {
                 print("Document does not exist")
            }
        }
    }      
}


func callingYourFunction() {

    self.getItems() { itemIDs in 
        if let ids = itemIDs {
          // itemIDs exists -> do whatever else you originally intended to do with the ids
          self.itemIDs = ids
        }
    }
}

如果您想了解更多关于闭包和完成处理程序的信息,请查看here!希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2019-06-15
    相关资源
    最近更新 更多