如何使用Swift @autoclosure [英] How to use Swift @autoclosure
问题描述
我注意到当在Swift中编写 assert
时,第一个值被输入为
@autoclosure() - > Bool
使用重载方法返回通用 T
c> value,通过 LogicValue
协议
测试存在。
但是严格遵守手头的问题。它似乎希望返回 Bool
的 @autoclosure
。
写一个没有参数并返回Bool的实际闭包不起作用,它希望我调用闭包来进行编译,如下所示:
assert({() - > Bool in return false}(),没有设置用户,file:__FILE__,line:__LINE__)
assert(false,No user has been set,file:__FILE__,line:__LINE__)
到底是怎么回事?什么是
@autoclosure
?
编辑:
@auto_closure 已重命名为
@autoclosure
解决方案一个函数接受一个参数,一个不带参数的简单闭包:
func f(pred:() - & ){
if pred(){
print(It's true)
}
}
要调用此函数,我们必须传入一个闭包
f :{2> 1})
//是真的
大括号,我们传入一个表达式,这是一个错误:
f(pred:2> 1)
//错误:'>'生成'Bool',而不是预期的上下文结果类型'() - > Bool'
@autoclosure
创建自动关闭周围的表情。所以当调用者写一个2> 1
,它会自动包装到一个闭包中,变成{2> 1}
,然后传递给f
。因此,如果我们将此应用于函数f
:func f pred:@autoclosure() - > Bool){
if pred(){
print(It's true)
}
}
f (pred:2> 1)
//这是真的
一个表达式,而不需要将其封装在闭包中。
I noticed when writing an
assert
in Swift that the first value is typed as@autoclosure() -> Bool
with an overloaded method to return a generic
T
value, to test existence via theLogicValue
protocol
.However sticking strictly to the question at hand. It appears to want an
@autoclosure
that returns aBool
.Writing an actual closure that takes no parameters and returns a Bool does not work, it wants me to call the closure to make it compile, like so:
assert({() -> Bool in return false}(), "No user has been set", file: __FILE__, line: __LINE__)
However simply passing a Bool works:
assert(false, "No user has been set", file: __FILE__, line: __LINE__)
So what is going on? What is
@autoclosure
?Edit:
@auto_closure
was renamed@autoclosure
解决方案Consider a function that takes one argument, a simple closure that takes no argument:
func f(pred: () -> Bool) { if pred() { print("It's true") } }
To call this function, we have to pass in a closure
f(pred: {2 > 1}) // "It's true"
If we omit the braces, we are passing in an expression and that's an error:
f(pred: 2 > 1) // error: '>' produces 'Bool', not the expected contextual result type '() -> Bool'
@autoclosure
creates an automatic closure around the expression. So when the caller writes an expression like2 > 1
, it's automatically wrapped into a closure to become{2 > 1}
before it is passed tof
. So if we apply this to the functionf
:func f(pred: @autoclosure () -> Bool) { if pred() { print("It's true") } } f(pred: 2 > 1) // It's true
So it works with just an expression without the need to wrap it in a closure.
这篇关于如何使用Swift @autoclosure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!