0

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")
                    }
                }
            }
        }))
}
Nick
  • 555
  • 2
  • 4
  • 13
  • 1
    the caller can provide a custom completion block to the setup function. Means, rhe caller will handle the result of the function. In the perform block, u just call the block that u passed to the function with the questions array as an parameter. – Björn Ro May 08 '17 at 06:05
  • 1
    Yes, it is possible. For usage check : https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html – Priyal May 08 '17 at 06:06
  • or you use a delegate. Where the class holds a delegate and this delegate will be called in the perform block. – Björn Ro May 08 '17 at 06:07

0 Answers0