Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 613
LearnCocos2D Avatar asked Dec 10 '14 15:12

LearnCocos2D


Video Answer


1 Answers

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.

like image 70
Martin R Avatar answered Nov 15 '22 05:11

Martin R