Why is the type-definition packed in parentheses? Can someone explain how this syntax has to be read?
// Definition & initialization
var removal: (() -> Void)? = nil
// Invocation of the closure
removal?()
(() -> Void)?
is an optional () -> Void
in the same way that Int?
is an optional Int
. You can also write this as Optional<() -> Void>
.
() -> Void
is wrapped in parentheses because () -> Void?
would mean a parameterless closure that returns an optional Void
(i.e. () -> Optional<Void>
).
Basically, ->
has a lower "precedence" than ?
.
In fact any type can be wrapped in parentheses can it will not change the meaning of that type. You can totally write (Int)
instead of Int
if you want. This is similar to how any expression can be wrapped in parentheses and it will not change the meaning of the expression.