I'm a swift and Firebase beginner, I met a problem that confuses me a lot. We all know the following code
var a = [Int]()
for i in 0..2{
a.append(i)
print(a)
print(a)
should give me the output
[0]
[0,1]
[0,1,2]
[0,1,2]
And it is true as the result. However, when I work on getDocument(), and I write a similar logic code, the output is strange! The code is the following.
override func viewDidLoad() {
super.viewDidLoad()
let docSecond = getThirtyData()
getDataContent(thirtyData: docSecond)
}
func getThirtyData()->Array<Int>{
var querySecond = [Int]()
var docSecond = [Int]()
let postDoc = db.collection("announcement")
postDoc.getDocuments { (querySnapshot, err) in
if let err = err{
print("Error getting documents: (err)")
}else{
for document in querySnapshot!.documents{
//print(document.data()["postTimeSecondInt"] as! Int)
querySecond.append(document.data()["postTimeSecondInt"] as! Int)
}
for _ in 1...querySecond.count{
let max = querySecond.max()!
docSecond.append(max)
let index = querySecond.firstIndex(of: max)
querySecond.remove(at: index!)
}
print(docSecond)
print("123")
}
}
print(docSecond)
print("456")
return docSecond
}
func getDataContent(thirtyData: [Int]){
print(thirtyData)
print("789")
}
I thought the result might come as same logic which is "123" print first, then "456", then "789". However, the result is like below.
[]
456
[]
789
[1588428987, 1588428980, 1588427392]
123
Seems like it run the code line below simultaneously with the for loop. Can anyone explain why this happens?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…