我有几个问题要问
1)什么是CompletionHandler和闭包,什么时候使用它? 2)闭包与CompletionHandler
这对我来说有点困惑。
发布于 2019-01-04 17:29:13
完成处理程序和闭包是同义词。它们在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
https://stackoverflow.com/questions/54035053
复制相似问题