【发布时间】:2019-01-04 07:58:16
【问题描述】:
我有一些问题,
1) 什么是 CompletionHandler 和 Closure 以及何时使用它? 2) 闭包 vs CompletionHandler
这让我有点困惑。
【问题讨论】:
标签: swift closures completionhandler
我有一些问题,
1) 什么是 CompletionHandler 和 Closure 以及何时使用它? 2) 闭包 vs CompletionHandler
这让我有点困惑。
【问题讨论】:
标签: swift closures completionhandler
完成处理程序和闭包是同义词。它们在 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
【讨论】: