Swift 类使用闭包省略括号:语法糖还是其他什么? [英] Swift class omitting brackets with closure: syntactic sugar or something else?

查看:45
本文介绍了Swift 类使用闭包省略括号:语法糖还是其他什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么我可以在类初始化中省略圆括号,因为它需要一个块作为参数.

I'm trying to understand why I can omit the round brackets in a class initialization when it takes a block as parameter.

不带括号的示例:

var block = CCActionCallBlock { () -> Void in
    NSLog("sedfjsdkl")
}

这是带括号的正式正确版本:

And here's the formally correct version with brackets:

var block = CCActionCallBlock ( { () -> Void in
    NSLog("sedfjsdkl")
})

两个变体都按预期工作,没有任何运行时错误或编译器警告.

Both variants work as expected, there aren't any runtime errors nor compiler warnings.

在什么情况下我可以省略类的初始化括号?这是相同的代码还是有任何副作用?关于闭包/块,还有其他我应该注意的语法糖吗?

Under which circumstances can I omit the class' initializer brackets? Is this the same code or does it have any side-effects? Are there any other syntactic sugars regarding closures/blocks I should be aware of?

注意:我知道作为最后一个参数的闭包可以写在括号之后,但找不到与省略括号相关的任何内容一共.

Note: I'm aware of the fact that a closure as last parameter can be written after the brackets, but can't find anything related to omitting the brackets altogether.

例如,我不能只是一般地省略类初始化括号,它似乎必须采用块/闭包作为语法糖工作的参数:

For instance I can't just generally omit the class init brackets, it seems to have to take a block/closure as parameter for the syntactic sugar to work:

var block = MyClass   // error, obviously ...

更新:显然 Xcode 会自动补全到没有括号的版本.

Update: Apparently Xcode autocompletes to the version without the brackets.

推荐答案

来自 闭包 在 Swift 参考中(强调):

From Closures in the Swift reference (emphasis added):

注意

如果提供闭包表达式作为函数的唯一参数并且您将该表达式作为尾随闭包提供,您不需要当你在函数名后写一对括号 ()调用函数.

If a closure expression is provided as the function’s only argument and you provide that expression as a trailing closure, you do not need to write a pair of parentheses () after the function’s name when you call the function.

这篇关于Swift 类使用闭包省略括号:语法糖还是其他什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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