我有一个结构“ Order”,其中包含一个名为orderId的字段:
protocol OrderSerializable {
init?(dictionary:[String:Any])
}
struct Order {
var orderId: String
var status: Int
var currentTotal: Double
var Dictionary:[String : Any] {
return [
"orderId": orderId,
"status": status,
"currentTotal": currentTotal
]
}
}
extension Order : OrderSerializable {
init?(dictionary: [String : Any]) {
guard let orderId = dictionary["orderId"] as? String,
let status = dictionary["status"] as? Int,
let currentTotal = dictionary["currentTotal"] as? Double
else { return nil }
self.init(orderId: orderId, status: status, currentTotal: currentTotal)
}
}
我需要将Firestore文档ID添加到模型数组中的orderId字段,即“ ordersArray”。我将如何去做?
到目前为止,这是我的查询代码,我已指出需要的行:
orderRef.getDocuments() {
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
guard let documents = querySnapshot?.documents else { return }
for document in documents {
let orderDictionary = document.data() as [String : Any]
let order = Order(dictionary: orderDictionary)
// Here I want to append the firestore documentId to order.orderId before appending it to the array
self.ordersArray.append(order!)
}
DispatchQueue.main.async {
self.ordersTableView?.reloadData()
}
}
}
谢谢。
答案 0 :(得分:1)
修改扩展名以接受documentId
作为附加参数,并将其传递给创建的Order对象。
protocol OrderSerializable {
init?(dictionary:[String:Any], id: String)
}
extension Order : OrderSerializable {
init?(dictionary: [String : Any], id: String) {
guard let status = dictionary["status"] as? Int,
let currentTotal = dictionary["currentTotal"] as? Double
else { return nil }
self.init(orderId: id, status: status, currentTotal: currentTotal)
}
}
然后,在创建每个订单时,将documentId
作为id
参数。
orderRef.getDocuments() {
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
} else {
guard let documents = querySnapshot?.documents else { return }
for document in documents {
let orderDictionary = document.data() as [String : Any]
let order = Order(dictionary: orderDictionary, id: document.documentId)
self.ordersArray.append(order!)
}
DispatchQueue.main.async {
self.ordersTableView?.reloadData()
}
}
}
或者,您可以将orderId
直接存储在文档本身中,以便将其与字典一起传递,从而避免了使用documentId
的需要。