Game Development Reference
In-Depth Information
println(mathFunction(5,5))
mathFunction = getMathFunction("*")
println(mathFunction(5,5))
mathFunction = getMathFunction("/")
println(mathFunction(5,5))
Passing Functions As Parameters
Swift also gives you the ability to pass functions to other functions. It uses a similar syn-
tax as you would use when you return a function. The following function definition takes
three parameters including two Int parameters and a function named mathFunction
and returns a single Int :
func performOperation(num1: Int, num2: Int, mathFunction:
(Int, Int) ->Int ) ->Int {
}
Notice the third parameter. It looks just like the return type you defined when you re-
turned a math function. The difference this time is you have to name the parameter that
will hold the passed-in function. In this case, you are storing the function in the math-
Function parameter. Let's implement and use this function.
func performOperation(num1: Int, num2: Int, mathFunction:
(Int, Int) ->Int) ->Int{
return mathFunction(num1, num2)
}
func multiply(num1: Int, num2 :Int) ->Int {
return num1 * num2
}
println(performOperation(100, 6, multiply))
The implementation of the performOperation() function is simple. It takes the two
Int s passed to it, passes those values to the passed-in function, and returns the result.
After the performOperation() function, you define another function that multiplies
two Int s and returns the result. To invoke the performOperation() function, you
pass it a 100 and a 6 along with the multiply() function. Go ahead and try it. Replace
Search WWH ::




Custom Search