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/