自动闭包

来源:互联网 发布:jdbc怎么连接mysql 编辑:程序博客网 时间:2024/05/21 10:47

定义
An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
autoclosure是一种闭包,自动创建一个闭包用来包裹一个表达式,它可以作为一个参数传入一个函数。当闭包被调用的时候,不带有任何参数并且返回包裹在闭包中的表达式的值。这种语法方便让您可以通过编写一个正常表达式而不是显式闭包来忽略函数形参的括号。
正常使用闭包
这里写图片描述
把闭包作为参数
这里写图片描述
自动闭包
serve(customer:)上面的列表中 的函数采用返回客户名称的显式闭包。下面的版本serve(customer:)执行相同的操作,但是,它采取自动闭包,而不是采取显式闭包,通过标记其参数的类型与@autoclosure属性。现在你可以调用函数,就像它接受一个String参数,而不是一个闭包。参数将自动转换为闭包,因为customerProvider参数的类型标记有@autoclosure属性。
这里写图片描述
注意
1.It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it.
使用自动闭包前提是:闭包不包含任何的参数。当闭包被调用的时候,返回的是包裹在闭包中的表达式的值。
2.Overusing autoclosures can make your code hard to understand. The context and function name should make it clear that evaluation is being deferred.过度的使用自动闭包可以导致代码很难理解,函数和上下文应该清楚表明计算正在推迟。

0 0
原创粉丝点击