无返回类型的单行闭包 [英] One-line closure without return type

查看:27
本文介绍了无返回类型的单行闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,如果一个闭包只包含一条语句,它会自动返回从这条语句返回的值.

In Swift, if a closure holds only a single statement, it automatically returns the value returned from that single statement.

这在所有情况下都不是很自然.我们来看一个例子:

This does not feel very natural in all cases. Let's look at an example:

func StringReturningFunc() -> String {
    return "Test String"
}

// Error: Cannot convert the expressions type '() -> $T0' to type 'String'
let closure: () -> () = {
    StringReturningFunc()
}

如您所见,即使闭包应该只调用一个简单的函数,它也会尝试自动返回它的返回值,该值属于 String 类型,并且与返回类型 无效.

As you can see, even though the closure should only call a simple function, it tries to automatically return it's return value, which is of type String, and does not match the return type void.

我可以通过像这样实现闭包主体来防止这种情况:

I can prevent this by implementing the closures body like so:

let _ = StringReturningFunc()

这感觉非常奇怪.

有没有更好的方法来做到这一点,或者这只是我不得不忍受的事情?

Is there a better way to do this or is this just something I have to live with?

推荐答案

发生这种情况的原因是单行表达式闭包的简写.在您的闭包中,有一个隐含的返回".

The reason this happens is the shorthand for single line expression closures. There is an implicit 'return' in your closure as it is written.

let closure: () -> () = {
    StringReturningFunc()
    return
}

这样写应该可以

这篇关于无返回类型的单行闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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