【问题标题】:How to return array in Swift after appending stuff to it?向数组追加内容后如何在 Swift 中返回数组?
【发布时间】:2020-06-20 23:47:10
【问题描述】:

我正在尝试根据从 Firebase 上的文档集合下载的数据构建一组项目。我从一个空数组开始,然后对于每个文档,我根据从该文档下载的数据创建一个项目,并将该项目附加到数组中。但是,它返回一个空数组。我觉得我需要用完成处理程序做一些事情,但我不太明白如何做到这一点。下面是我的代码。谢谢!

func getDayData() -> [Item] {
    var myList = [Item]()
    let docs = Firestore.firestore().collection("Users").document("pK0tVBXvbFNhTZic3PIM").collection("Log").document("18-06-2020").collection("Items")
    docs.getDocuments() {(querySnapshot, err) in
        if let err = err {
            //TODO
        } else {
            for document in querySnapshot!.documents {
                myList.append(Item(id: document.documentID, item: document.get("Item") as! String, category: document.get("Category") as! String, pieces: document.get("Pieces") as! Int))
            }
        }
    }
    return myList
}

【问题讨论】:

  • 你确定那些append 电话真的发生了吗?在那里设置断点可能是值得的。他们可能都掉进了那个“TODO”的洞里。

标签: swift firebase swiftui completionhandler


【解决方案1】:

您不能等待异步方法完成。您需要为您的方法添加一个完成处理程序:

func getDayData(completion: @escaping ([Item]?, Error?) -> Void) {
    Firestore.firestore()
        .collection("Users")
        .document("pK0tVBXvbFNhTZic3PIM")
        .collection("Log")
        .document("18-06-2020")
        .collection("Items")
        .getDocuments() { querySnapshot, error in
        let items = querySnapshot?.documents.map {
            Item(id: $0.documentID,
                 item: $0.get("Item") as? String ?? "",
                 category: $0.get("Category") as? String ?? "",
                 pieces: $0.get("Pieces") as? Int ?? 0)
        }
        completion(items, error)
    }
}

用法:

getDayData { items, error in
    guard let items = items else { 
        print(error ?? "nil")
        return 
    }
    // use items here

}

【讨论】:

  • 如果我想显示这些项目的列表怎么办?我尝试 getDayData { items, err in guard let items = items else { print(err ?? "nil") return } List(items){ item in ZStack{ Text(item.item) //OTHER STUFF... } } .padding(.trailing) },但我得到错误类型“()”不能符合“视图”;只有结构/枚举/类类型可以符合协议
  • 我不习惯 SwiftUI 但是尝试一下List {Text("Items")ForEach(items) { item inText(item.item)}} 或者可能是List {Text("Items")79654332@30@79654332@98 @}
猜你喜欢
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多