I was wondering if there is a way to return information back from within a completion block in Swift. I have the written the following function below and I would like to use the variable "allQuestions" outside of the completion block. Is this possible, and if so, how could I go about it?
func setupQuestions() {
var allQuestions = [Question]()
var A: String = ""
var B: String = ""
var C: String = ""
var D: String = ""
var topic: String = ""
var answer:String = ""
var quest_name:String = ""
var container: CKContainer
var publicDB: CKDatabase?
container = CKContainer.default()
publicDB = container.publicCloudDatabase
let Predicate = NSPredicate(format: "Topic = 'Maths'")
let query = CKQuery(recordType: "Question", predicate: Predicate)
publicDB?.perform(query, inZoneWith: nil, completionHandler: ({results, error in
if (error != nil) {
DispatchQueue.main.async() {
print(error!.localizedDescription)
}
} else {
if results!.count > 0 {
var temp: Question
for i in 1...(results!.count) {
A = results?[i].object(forKey: "A") as! String
B = results?[i].object(forKey: "B") as! String
C = results?[i].object(forKey: "C") as! String
D = results?[i].object(forKey: "D") as! String
topic = results?[i].object(forKey: "Topic") as! String
answer = results?[i].object(forKey: "Answer") as! String
quest_name = results?[i].object(forKey: "Name") as! String
temp = Question(topic: topic, quest: quest_name, A: A, B: B, C: C, D: D, answer: answer)
allQuestions.append(temp)
}
} else {
DispatchQueue.main.async() {
print("No record matching the address was found")
}
}
}
}))
}