将2d阵列存储在Firestore中? [英] Store 2d Array in Firestore?

查看:33
本文介绍了将2d阵列存储在Firestore中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Firestore中保存/返回2D数组的最佳实践是什么?除了为每个数组创建一个新的集合外,还有一种更有效的说法将数据结构保持在一起吗?谢谢!

What's the best practice to save/return a 2d array in Firestore? Instead of creating a new collection for each array, is there a more efficient say of keeping the data structure together? Thanks!

struct appleCounter {
    var tree = [branches]
}

var branches = [Int]()

let treeFullOfApples = [[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]

let morningCount = appleCounter{
    tree: treeFullOfApples
}

推荐答案

结构应该非常简单

arrays //collection
   array_doc_0 //document
      array_0     //field
         0: 10
         1: 10
         2: 10
      array_1
         0: 10
         1: 10
         2: 10

然后是一个用于保存数组数组的类

Then a class to hold the array of arrays

class MyArrayClass {
    var myArrayOfArrays = [ [Int] ]()
}

在上面,myArrayOfArrays是一个变量,它将包含多个Int数组,如问题所示.

In the above, the myArrayOfArrays is a var that would contain multiple arrays of Int arrays, like shown in the question.

[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]

然后是从Firestore读取该结构并填充MyArrayClass对象的代码.

and then the code to read that structure from Firestore and populate a MyArrayClass object.

var myNestedArray = MyArrayClass()

let arraysCollection = self.db.collection("arrays")
let thisArrayDoc = arraysCollection.document("array_doc_0")
thisArrayDoc.getDocument(completion: { documentSnapshot, error in
    if let err = error {
        print(err.localizedDescription)
        return
    }

    guard let doc = documentSnapshot?.data() else { return }

    for arrayField in doc {
        let array = arrayField.value as! [Int]
        myNestedArray.myArrayOfArrays.append(array)
    }

    for a in myNestedArray.myArrayOfArrays { //output the arrays
        print(a)
    }
})

最终结果将是一个对象,该对象的var是一个数组数组.闭包的最后一部分遍历我们创建的对象,以验证其值是数组数组.输出是

The end result will be an object, that has a var that is an array of arrays. The last part of the closure iterates over the object we created to verify it's value is an array of arrays. The output is

[10, 10, 10]
[20, 20, 20]

这篇关于将2d阵列存储在Firestore中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆