Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 不带返回类型的单线闭合_Swift - Fatal编程技术网

Swift 不带返回类型的单线闭合

Swift 不带返回类型的单线闭合,swift,Swift,在Swift中,如果闭包只包含一条语句,它将自动返回从该语句返回的值 这并不是在所有情况下都很自然。让我们看一个例子: func StringReturningFunc() -> String { return "Test String" } // Error: Cannot convert the expressions type '() -> $T0' to type 'String' let closure: () -> () = { StringRet

在Swift中,如果闭包只包含一条语句,它将自动返回从该语句返回的值

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

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

// Error: Cannot convert the expressions type '() -> $T0' to type 'String'
let closure: () -> () = {
    StringReturningFunc()
}
正如您所看到的,即使闭包应该只调用一个简单函数,它也会尝试自动返回它的返回值,返回值的类型为String,并且与返回类型void不匹配

我可以通过如下方式实现闭包体来防止这种情况:

let _ = StringReturningFunc()
这感觉非常奇怪


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

发生这种情况的原因是单行表达式闭包的缩写。在编写闭包时,闭包中有一个隐含的“返回”

let closure: () -> () = {
    StringReturningFunc()
    return
}
这样写应该行得通

这个怎么样

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

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

我认为这是一个好问题。但是,添加一个新的解决方案可能会有所帮助,有更好的解决方案吗?为了阻止接近票数的投票。@CraigOtis编辑了我的问题,谢谢你的提示。我不明白这一点,当stringreturningfunc显式返回字符串时,你怎么能说闭包返回?@Edgararroutiounian仅仅因为闭包调用stringreturningfunc并不意味着它也应该返回字符串。这里它应该什么也不返回,而不是字符串。@EdgararRoutiounian他试图执行函数并放弃返回,但是单行闭包上有一个隐式的return语句。谢谢这个提示!如果OP仍然希望它是一行,那么可以使用let wrapped:->Void={stringReturningFunc;return}在不显式调用return的情况下,是否真的没有其他方法可以做到这一点?这难道不能在Swift编译器中修复吗,如果他们只是检测到闭包应该返回Void,因此没有尝试返回第一条语句?在所有其他不返回Void的闭包中,它可以使用隐式返回。@SandyChapman在其他语言中,不包括“return”只是隐式的“return Void”。你已经习惯了这个惯例,你也可以很容易地习惯这个惯例。对于像Swift这样的新语言来说,随着软件开发的不断发展,重新定义其中的一些约定是有好处的。从Xcode Beta版本6.3 6D520o开始,这些约定似乎已经被修复。“单表达式闭包的隐式返回”现在也适用于返回Void以外的内容的表达式。