DDR
DDR

Reputation: 103

Swift how to make a function execute after another function completed

I wrote two Swift functions (just a multiple choice quiz app)

func createQuestions() // this goes to Parse, and fetches the questions data that are going to question the users and store them into local arrays

func newQuestion() // this also fetches some other data (for example, some incorrect choices) from Parse and read local variables and finally set the labels to correctly display to the users

I want in ViewDidLoad, first execute createQuestion(), after it is fully completed then run newQuestion(). Otherwise the newQuestion() has some issues when reading from local variables that were supposed to be fetched. How am I going to manage that?

EDIT: I learned to use closure! One more follow up question. I am using a for loop to create questions. However, the problem is that the for loop does not execute orderly. Then my check for repeated function (vocabTestedIndices) fails and it would bring two identical questions. I want the for loop to execute one by one, so the questions created will not be overlapped. code image

Upvotes: 9

Views: 18634

Answers (4)

Nguyen Hoan
Nguyen Hoan

Reputation: 1693

try

override func viewDidLoad() {
    super.viewDidLoad()
    self.createQuestions { () -> () in
        self.newQuestion()
    }
}


func createQuestions(handleComplete:(()->())){
    // do something
    handleComplete() // call it when finished stuff what you want 
}
func newQuestion(){
    // do other stuff
}

Upvotes: 13

Kiran Jasvanee
Kiran Jasvanee

Reputation: 6554

Closure will help you to achieve this functionality.
Create your createQuestions function as below.

func createQuestions(completion:((Array<String>) -> ())){

    //Create your local array for storing questions
    var arrayOfQuestions:Array<String> = []

    //Fetch questions from parse and allocate your local array.
    arrayOfQuestions.append("Question1")

    //Send back your questions array to completion of this closure method with the result of question array.
    //You will get this questions array in your viewDidLoad method, from where you called this createQuestions closure method.
    completion(arrayOfQuestions)
}  

viewDidLoad

override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        //Calling createQuestions closure method.
        self.createQuestions { (arrayOfQuestions) -> () in

            //Pass your local questions array you received from createQuestions to newQuestion method.
            self.newQuestion(arrayOfQuestions)
        }
    }  

New Question Method

func newQuestion(arrayOfQuestions:Array<String>){

        //You can check your questions array here and process on it according to your requirement.
        print(arrayOfQuestions)
    }

Upvotes: 0

aaisataev
aaisataev

Reputation: 1683

What about swift defer from this post?

func deferExample() {
    defer {
        print("Leaving scope, time to cleanup!")
    }
    print("Performing some operation...")
}

// Prints:
// Performing some operation...
// Leaving scope, time to cleanup!

Upvotes: 8

Bibek
Bibek

Reputation: 3719

Since you are new. I don't know if you do know closures or not so i have placed simple solution for you. (solution is similar to @Paulw11 commented on your question) just call in viewDidLoad:

self.createQuestions()

The task you want to perform depends on the Parse response:
only after response arrives you want to call newQuestion function.

Here is the Parse Documentation for swift: https://www.parse.com/docs/ios/guide#objects-retrieving-objects

func createQuestions() {
    var query = PFQuery(className:"GameScore")
    query.whereKey("playerName", equalTo:"Sean Plott")
    query.findObjectsInBackgroundWithBlock {
      (objects: [PFObject]?, error: NSError?) -> Void in

      if error == nil {
        // The find succeeded.

        self.newQuestion()        
      } else {
        // Log details of the failure
        print("Error: \(error!) \(error!.userInfo)")
      }
    }
}

func newQuestion() {
 //here is your code for new question function
}

Upvotes: 0

Related Questions