Optional trailing closures in Swift
Swift language has a handy feature called trailing closures
.
It is a clean way of passing a closure into a function.
func makeTea(doNext: () -> ()) {
// making tea ...
doNext()
}
We can then call the function this way.
makeTea { drinkTea() }
Here we call makeTea
function and pass a closure expression drinkTea()
into it.
Notice that we did not write parentheses ()
when calling makeTea
, which
is allowed if there are no other parameters.
Making trailing closure optional
But what if we don’t always need to pass a closure into our function? It is achieved by
- making parameter an optional type
(...)?
, - using nil for its default value ` = nil` and
- calling parameter using optional chaining
?()
.
func makeTea(doNext: (() -> ())? = nil) {
// making tea ...
doNext?()
}
Now we can call makeTea
function without supplying the closure.
makeTea()
Posted by Evgenii