【问题标题】:How can I make a function complete before calling others in an IBAction?在 IBAction 中调用其他函数之前,如何使函数完成?
【发布时间】:2016-02-29 14:37:39
【问题描述】:

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

我有一个 textFieldEditingDidChange IBAction,它首先在文本字段输入 上调用 verify() 函数,然后在 apply 返回的布尔值上调用 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
}

如何在验证已计时执行后进行打印语句或任何代码? 谢谢

【问题讨论】:

    标签: swift asynchronous swift2 completionhandler


    【解决方案1】:

    类似这样的:

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

    注意:如果您说“在服务器上获取字符串“orlando”的某些代码”,请注意不要在异步调用之后设置新的completion,否则您仍然会遇到同样的问题... 完成应该在与异步调用结果相同的范围内使用。

    【讨论】:

    • 非常感谢,它有效。你的笔记也很有帮助,因为我完全按照你的预期做了错误。现在工作正常。
    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    相关资源
    最近更新 更多