在 IBAction 中调用其他函数之前如何完成一个函数?

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

我无法理解完成处理程序。

我有一个 textFieldEditingDidChange IBAction,它首先在文本字段输入上调用 verify() 函数 ,然后在布尔值上调用 if 语句通过申请返回。 问题是 if 语句在 verify() 完成之前开始

代码如下:

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

我怎样才能使打印语句或任何代码在验证已定时执行后发生?? 谢谢

像这样:

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

然后您在 IBAction 中这样调用它,并带有尾随闭包:

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

注意:你在服务器上说"some code that fetches a string "orlando"的地方,注意不要在异步调用completion之后设置新的completion,否则您仍然会遇到同样的问题... 完成应该在与异步调用结果相同的范围内使用。