Swift如何在另一个函数完成后执行函数

时间:2016-01-25 04:29:03

标签: ios swift

我写了两个Swift函数(只是一个多项选择测验应用程序)

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()在读取应该获取的局部变量时会出现一些问题。我该如何管理?

编辑:我学会了使用关闭!还有一个跟进问题。我正在使用for循环来创建问题。但是,问题是for循环不能有序执行。然后我对重复功能(vocabTestedIndices)的检查失败了,它会带来两个相同的问题。我希望for循环逐个执行,因此创建的问题不会重叠。 code image

4 个答案:

答案 0 :(得分:8)

尝试

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


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

答案 1 :(得分:4)

来自this post的swift defer怎么样?

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

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

答案 2 :(得分:0)

因为你是新人。我不知道你是否知道关闭,所以我已经为你提供了简单的解决方案。 (解决方案类似于@ Paulw11对您的问题发表评论) 只需在viewDidLoad中调用:

self.createQuestions()

您要执行的任务取决于Parse响应:
只有在响应到达后你才想调用newQuestion函数。

以下是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
}

答案 3 :(得分:0)

Closure将帮助您实现此功能 创建您的createQuestions函数,如下所示。

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)
        }
    }  

新问题方法

func newQuestion(arrayOfQuestions:Array<String>){

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