Generally speaking, Firebase / Firestore rely a lot on key: value pairs, much like one would find in a Dictionary.
Dictionaries are unordered... so this
document?.data()
contains your data but it's not ordered and will vary from read to read.
One option to guarantee order is to store the values in an array.
I don't know what your Firestore structure is but suppose we have a document with several fields that contain arrays
arrays // collection
array_doc_0 //document
array_0 /field
0: 1
1: 2
2: 3
array_1
0: 4
1: 5
2: 6
To read those in and print them to console, here's the code. Note that the content of the arrays will always be in the correct sequence, guaranteed by their array index.
func readSomeArrays() {
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]
for i in array {
print(i)
}
}
})
}
and the output
[4, 5, 6]
[1, 2, 3]
note that array_1 printed before array_0. This is because again, the documentSnapshot.data() is an unordered 'Dictionary', which we are iterating over. It wasn't clear if that ordering was important but if so, store the arrays in an array, or create your own index and sort in code.