standousset
standousset

Reputation: 1161

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

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

Upvotes: 3

Views: 264

Answers (1)

Eric Aya
Eric Aya

Reputation: 70118

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.

Upvotes: 3

Related Questions