Got A Problem With Swift Function
I wrote a function, and I called it within .onAppear {}
. But it returned a value before executing the main body of the function. I'm new to Swift, and I cannot finger it out.
Here is the function definition:
func getUnapprovedCourses(account: String) -> [Course] {
print("===== [1] Main body of the function ===== \n")
let db = Firestore.firestore()
var coursesArray: [Course] = []
db.collection("temp_courses").whereField("teach_by", isEqualTo: account)
.getDocuments() { (querySnapshot, err) in
for document in querySnapshot!.documents {
do {
let singleCourse: Course = try document.data(as: Course.self)
print("===== [2] Append an element ===== \n")
coursesArray.append(singleCourse)
} catch {
print("Place A error... [ FirestoreManager.swift -> UserManager -> getUnapprovedCourses ]")
}
// print("\(document.documentID) => \(document.data())")
}
}
print("===== [3] Return an array ===== \n")
return coursesArray
}
And I called the function in this way
.onAppear {
getCouresesInfo()
}
// getCoursesInfo()
func getCoursesInfo() {
let userManager = UserManager()
print("===== [0] Call the function ===== \n")
coursesArray = userManager.getUnapprovedCourses(account: account)
}
And here are the results printed in the console:
===== [0] Call the function =====
===== [1] Main body of the function =====
===== [3] Return an array =====
===== [2] Append an element =====
It returned first and then appended elements. I hope someone can help me out. :) Thx.
I wish it could append some elements to that array coursesArray
, then return the value.