My function has this signature:
func foo(bar: String, baz: ((String) -> ())? = nil)
And now I want to make unecessary to escape self
inside the given closure.
But when I try this:
func foo(bar: String, @noescape baz: ((String) -> ())? = nil)
The compiler complains:
@noescape may only be applied to parameters of function type
Is it possible to use it in optional parameters?
Requirements
If your requirements are the following:
baz
param is aclosure
baz
param is marked with@noescape
(because you want to omitself
in the closure code)baz
param can be omitted during the invocation offoo
Solution
Then you can use the following syntax
As you can see the main difference from your code is that:
baz
is not anoptional type
(but it's an "optional parameter")empty closure
not anil
value.Examples
As you requested you can now pass a closure to
baz
without the need of usingself
And you can also omit the
baz
paramUpdate: using a closure with return type different from Void
In a comment below users
TadeasKriz
asked about how to use this approach with a closure having the return value different theVoid
.Here it is the solution
Here the
baz
param does required a closure with 1 param of typeString
and a return value of typeInt
. As you can see I added a default value to the param, a closure that does return0
. Please note that the default closure will never be used so you can replace0
with anyInt
value you want.Now you can decide whether to use pass your closure to the
baz
paramOr, again, you can totally omit the
baz
param.