[英]Swift class omitting brackets with closure: syntactic sugar or something else?
I'm trying to understand why I can omit the round brackets in a class initialization when it takes a block as parameter. 我试图理解为什么我可以在类初始化中省略圆括号时将块作为参数。
Example without the brackets: 没有括号的示例:
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: 例如,我不能只是通常省略类init括号,它似乎必须采用块/闭包作为语法糖的工作参数:
var block = MyClass // error, obviously ...
Update: Apparently Xcode autocompletes to the version without the brackets. 更新:显然Xcode自动填充到没有括号的版本。
From Closures in the Swift reference (emphasis added): 来自Swift参考中的闭包 (强调添加):
NOTE
注意
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.
如果提供闭包表达式作为函数的唯一参数,并且您将该表达式作为尾随闭包提供,则在调用函数时, 不需要在函数名称后面写一对括号()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.