Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: how to optionally pass function as parameter and invoke the function?

Tags:

ios

swift

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?

like image 230
Crashalot Avatar asked May 01 '15 04:05

Crashalot


1 Answers

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 ...
    }
}
like image 134
matt Avatar answered Sep 18 '22 13:09

matt