swift逃逸闭包

定义
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.
闭包描述为:当闭包作为参数被传递到一个函数的时候,但是调用却在函数return之后。当你声明一个函数,这个函数把闭包作为它的一个参数,你可以把@escaping关键字写在在参数类型之前来表明这个闭包允许逃逸。
应用
One way that a closure can escape is by being stored in a variable that is defined outside the function. As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn’t called until the operation is completed—the closure needs to escape, to be called later. For example:
一种情况下闭包可以逃逸,闭包被存储在定义在函数外边的变量里边。例如:许多开启异步操作的函数把闭包作为完成处理程序。这个函数在开启这个异步操作之后就已经return了。但是这个闭包并不发生调用直到异步操作完成。要实现闭包后来被调用的功能,闭包需要逃逸。例如:
这里写图片描述
The someFunctionWithEscapingClosure(_:) function takes a closure as its argument and adds it to an array that’s declared outside the function. If you didn’t mark the parameter of this function with @escaping, you would get a compile-time error.

Marking a closure with @escaping means you have to refer to self explicitly within the closure. For example, in the code below, the closure passed to someFunctionWithEscapingClosure(:) is an escaping closure, which means it needs to refer to self explicitly. In contrast, the closure passed to someFunctionWithNonescapingClosure(:) is a nonescaping closure, which means it can refer to self implicitly.
这个函数把一个闭包做为他的一个参数并且把闭包添加到函数外边声明的一个数组中。如果你不标记这个参数为逃逸闭包的话,你将会得到一个编译错误。
创建一个逃逸闭包意味着你在闭包内部必须显示的引用self。相反,someFunctionWithNonescapingClosure(_:)是一个非逃逸闭包,这意味着它可以隐式地引用自己。
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值