简体   繁体   中英

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:

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

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

From Closures in the Swift reference (emphasis added):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM