Here's another example. This shows how a function requires you to provide:
- Two integers
- A function
What function does it require? The signature doesn't specify what the function needs to do. It only specifies the function needs to accept two integer, then return an integer. You can provide any function you want. It just has to conform to these rules.
But this example also shows several ways to provide that required function!
Three examples show how the function is passed in as a parameter. The other two examples show how to pass in the function using trailing closure syntax.
Paste this code into Playgrounds. See if this adds to the excellent answer posted above.
func applyFunction(to lhs: Int, and rhs: Int, thisFunction someFunction: (Int, Int) -> Int ) -> Int {
// pass in the left hand side and right hand side values.
// then perform the function with those values passed in.
// I have no idea what the function does, but I'll run it anyway.
return someFunction(lhs, rhs) //
}
func sekretFunction(x: Int, y: Int) -> Int { x * y } // shhhh! sekret!
let answer01 = applyFunction(to: 22, and: 20, thisFunction: { $0 + $1 } ) // provide a closure via the initializer
let answer02 = applyFunction(to: 40, and: 2) { $0 * 2 + $1 } // provide a closure using trailing closure syntax
let answer03 = applyFunction(to: 44, and: 2, thisFunction: sekretFunction ) // provide a function via initializer
let answer04 = applyFunction(to: 20, and: 5) { sekretFunction(x: $0, y: $1) } // provide a function via closure
let answer05 = applyFunction(to: 60, and: 20, thisFunction: / ) // Divide! it's a function that takes two ints and returns an int