如何使用Swift @autoclosure [英] How to use Swift @autoclosure

查看:139
本文介绍了如何使用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 the LogicValue protocol.

However sticking strictly to the question at hand. It appears to want an @autoclosure that returns a Bool.

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 like 2 > 1, it's automatically wrapped into a closure to become {2 > 1} before it is passed to f. So if we apply this to the function f:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆