完成处理程序和闭包



我在这里有一些问题,

1) 什么是 CompletionHandler 和 Closure 以及何时使用它?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()
完成处理程序

只是用于完成某个操作的闭包:完成某些操作后,调用完成处理程序,该处理程序执行代码以完成该操作。

这只是一个基本的解释,有关更多详细信息,您应该查看文档:https://docs.swift.org/swift-book/LanguageGuide/Closures.html

最新更新