Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to make a function execute after another function completed

Tags:

ios

swift

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

like image 520
DDR Avatar asked Jan 25 '16 04:01

DDR


2 Answers

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
}
like image 171
Nguyen Hoan Avatar answered Nov 08 '22 21:11

Nguyen Hoan


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!
like image 8
aaisataev Avatar answered Nov 08 '22 21:11

aaisataev