Swift如何让一个函数在另一个函数完成之后执行 [英] Swift how to make a function execute after another function completed

查看:56
本文介绍了Swift如何让一个函数在另一个函数完成之后执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了两个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

我要在 ViewDidLoad 中,首先执行 createQuestion(),完全完成后再运行 newQuestion().否则, newQuestion()在读取应该获取的局部变量时会出现一些问题.我该如何处理?

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?

我学会了使用闭包!还有一个后续问题.我正在使用for循环来创建问题.但是,问题在于for循环无法按顺序执行.然后,我对重复功能(vocabTestedIndices)的检查失败了,它将带来两个相同的问题.我希望for循环一个接一个地执行,因此创建的问题不会重叠.代码图像

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

推荐答案

尝试

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
}

这篇关于Swift如何让一个函数在另一个函数完成之后执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆