CompletionHandler和闭包

时间:2019-01-04 07:58:17

标签: swift closures completionhandler

我在这里有一些问题,

1)什么是CompletionHandler和Closure以及何时使用它? 2)闭包与CompletionHandler

对我来说有点困惑。

1 个答案:

答案 0 :(得分:2)

完成处理程序和闭包是同义词。在Objective-C中它们被称为块。

您可以将它们视为被调用时执行一大堆代码的对象(很像一个函数)。

// My view controller has a property that is a closure
// It also has an instance method that calls the closure
class ViewController {

    // The closure takes a String as a parameter and returns nothing (Void)
    var myClosure: ((String) -> (Void))?
    let helloString = "hello"

    // When this method is triggered, it will call my closure
    func doStuff() {
        myClosure(helloString)?
    }
}

let vc = ViewController()

// Here we define what the closure will do when it gets called
// All it does is print the parameter we've given it
vc.myClosure = { helloString in
    print(helloString) // This will print "hello"
}

// We're calling the doStuff() instance method of our view controller
// This will trigger the print statement that we defined above
vc.doStuff()

完成处理程序只是用于完成某个动作的闭包:完成某件事后,您将调用执行代码来完成该动作的完成处理程序。

这只是一个基本说明,有关更多详细信息,请查看文档:{​​{3}}