How can you optionally pass in a function to another function? Concretely, assume functionA accepts as a parameter functionB. If functionB is not nil, how can you execute functionB inside of functionA?
Hard to see what's hard about this, so maybe this isn't what you mean, as it seems so trivially obvious; but anyway, here goes:
func optionalFunctionExpecter(f:(()->())?) {
f?()
}
Here's how to call it with an actual function:
func g() {
println("okay")
}
optionalFunctionExpecter(g)
Or, calling it with an actual anonymous function:
optionalFunctionExpecter { println("okay2") }
Here's how to call it with nil
:
optionalFunctionExpecter(nil)
Observe that in my implementation of optionalFunctionExpecter
, when called with nil
, nothing will happen: we won't call f
, we won't crash, we won't do anything. If you need to know that nil
was passed, you can readily find out: just ask, in optionalFunctionExpecter
, whether f == nil
and proceed on that basis as desired. For more flexibility, we could rewrite like this:
func optionalFunctionExpecter(f:(()->())?) {
if let f = f {
f()
} else {
// ... nil was passed, respond to that fact ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With