1

Is it possible to call a function as a parameter of another function in Swift??

I am making a sound effects app in Swift which uses different effects like AVAudioUnitReverb() and AVAudioUnitDistortion() etc. I wanted to create a single function and just be able to call which effects I wanted to do.

1
  • You can pass a function as a parameter of a function. You can either pass the function directly or by its name. Commented Nov 11, 2015 at 12:59

3 Answers 3

6

Because in Swift functions are first-class types, you can pass it as an argument to another function.

Example:

func testA() { print("Test A") } func testB(function: () -> Void) { function() } testB(testA) 
Sign up to request clarification or add additional context in comments.

Comments

1

You can pass in functions as parameter my typing the parameter with the same signature.

As sunshine's example just deals with Void parameters and return types, I want to add another example

func plus(x:Int, y:Int) -> Int { return x + y } func minus(x:Int, y:Int) -> Int { return x - y } func performOperation (x:Int, _ y:Int, op:(x:Int,y: Int) -> Int) -> Int { return op(x: x, y: y) } let resultplus = performOperation(1, 2, op: plus) // -> 3 let resultminus = performOperation(1, 2, op: minus) // -> -1 

note: Of course you should consider dynamic typed parameters. For simplicity here just Ints

this is called Higher Order Functions and in many languages this is the way of doing it. But often you don't won't to explicitly create functionss for it. Here Closures are a perfect tool:

The function performOperation stays untouched, but the operations are implemented differently:

let plus = { (x:Int, y:Int) -> Int in return x + y } let minus = { (x:Int, y:Int) -> Int in return x - y } let resultplus = performOperation(1, 2, op: plus) let resultminus = performOperation(1, 2, op: minus) 

Often this would be preferred as it doesn't need methods to be added to a class, pretty much like anonymous functions in other languages.


More on this and how it is used in the swift standard library: https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/

Comments

1

I would recommend book "IOS 9 Programming Fundamentals with Swift" by Matt Neuburg, especially subchapter "Functions".

You should not only find the answer for your question:

func imageOfSize(size:CGSize, _ whatToDraw:() -> ()) -> UIImage { ... } 

But also how to construct function that returns the function:

func makeRoundedRectangleMaker(sz:CGSize) -> () -> UIImage { ... } 

As well as brief introduction to Curried Functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.