swift基础之逃逸和自动闭包

原创
2021/04/12 15:59
阅读数 53

逃逸闭包

当闭包作为一个实际参数传递给一个函数的时候,并且它会在函数返回之后调用,就说这个闭包逃逸了。常用在接收闭包实际参数来作为启动异步任务的回调。

自动闭包

是一种自动创建的用来把作为实际参数传递给函数的表达式打包的闭包。它不接受任何实际参数,并且当它被调用时,它会返回内部打包的表达式的值。

示例:

//添加autoclosure关键字
func assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String()) {
    if !condition(){
        print(message())
    }
}

assert(5 > 6, "error")

//自动闭包允许延迟处理
var persons = ["zhang san", "li si", "wang wu", "zhao liu"]
print(persons.count)
//4

let deletePerson = { persons.remove(at: 0) }
print(persons.count)
//4

deletePerson()
print(persons.count)
//3

//闭包作为实参
func serve(customer customerProvider: () -> String) {
    print("Now serving \(customerProvider())!")
}
serve(customer: { persons.remove(at: 0) })
//Now serving li si!

//自动闭包作为实参
func serveTwo(customer customerProvider: @autoclosure () -> String) {
    print("Now serving \(customerProvider())!")
}
serveTwo(customer:  persons.remove(at: 0))
//Now serving wang wu!

//自动闭包允许逃逸
var customersInLine = ["zhang san", "li si", "wang wu", "zhao liu"]
var customerProviders: [() -> String] = []
func collectCustomerProviders(_ customerProvider: @autoclosure @escaping () -> String) {
    customerProviders.append(customerProvider)
}
collectCustomerProviders(customersInLine.remove(at: 0))
collectCustomerProviders(customersInLine.remove(at: 0))

print("Collected \(customerProviders.count) closures")
for c in customerProviders {
    print("Now serving \(c())!")
}
/*
 Collected 2 closures
 Now serving zhang san!
 Now serving li si!
 */
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部