我怎样才能让一个函数在IBAction为别人打电话之前完成? [英] How can I make a function complete before calling others in an IBAction?

查看:155
本文介绍了我怎样才能让一个函数在IBAction为别人打电话之前完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解完成处理。

我有一个textFieldEditingDidChange IBAction为,首先调用验证()在文本框输入功能,然后在if语句在返回的布尔适用。 的问题是,if语句开始验证()之前已完成

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.

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

我怎样才能使打印语句,或任何code,正好后验证已定时执行?
谢谢

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

推荐答案

事情是这样的:

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为这样的,有一个尾随封:

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

请注意:在您说一些code,它取一个字符串服务器上的奥兰多,要小心不要设置新的完成之后的异步调​​用,否则你将仍然遇到了同样的问题... 的完成应在同一范围内的异步调用的结果被使用。

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.

这篇关于我怎样才能让一个函数在IBAction为别人打电话之前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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