How can I make a function complete before calling others in an IBAction?

半世苍凉 提交于 2019-12-22 09:48:01

问题


I'm having trouble understanding completion handlers.

I have a textFieldEditingDidChange IBAction that calls first a verify() function on the textfield input and then an if statement on the boolean returned by apply. The problem is that the if statement starts before verify() has finished.

Here is the code:

@IBOutlet weak var myTextField: UITextField!

@IBAction func myTextFieldEditingDidChange(sender: AnyObject) {

        let yo = verify(myTextField.text!)            
        print("\(yo)") // it always prints "true" because verify hasn't finished

}


func verify(myText: String) -> Bool {
    var result = true
    // some code that fetches a string "orlando" on the server
    if myText == "orlando" {
         result = false
    }
    return result
}

How can i make the print statement, or any code, happen after verify has had timed to execute ?? Thanks


回答1:


Something like this:

func verify(myText: String, completion: (bool: Bool)->()) {
    var result = true
    // some code that fetches a string "orlando" on the server
    if myText == "orlando" {
        result = false
    }
    completion(bool: result)
}

And you call it in your IBAction like this, with a trailing closure:

verify(myTextField.text!) { (bool) in
    if bool {
        // condition in `verify()` is true
    } else {
        // condition in `verify()` is false
    }
}

Note: where you say "some code that fetches a string "orlando" on the server", be careful to not set the new completion after the async call, otherwise you would still experience the same issue... The completion should be used in the same scope as the async call result.



来源:https://stackoverflow.com/questions/35702286/how-can-i-make-a-function-complete-before-calling-others-in-an-ibaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!