Store 2d Array in Firestore?

徘徊边缘 提交于 2020-01-25 07:18:43

问题


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
}

回答1:


The structure should be fairly straightforward

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] ]()
}

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]]

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)
    }
})

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]


来源:https://stackoverflow.com/questions/57296264/store-2d-array-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!