Game Development Reference
In-Depth Information
}
func subtract(num1: Int, num2 :Int) ->Int {
return num1 - num2
}
func multiply(num1: Int, num2 :Int) ->Int {
return num1 * num2
}
func divide(num1: Int, num2 :Int) ->Int {
return num1 / num2
}
switch (op) {
case "+" : return add
case "-" : return subtract
case "*" : return multiply
default : return divide
}
}
This function has the same definition you saw earlier, but it has an implementation now.
As you look over the implementation, you will see four nested functions matching the re-
turn type of
getMathFunction()
. They each take two
Int
parameters, and they all
return a single
Int
.
After the nested functions, you will see a simple
switch
statement that tests the passed-
in character and returns a nested function based upon the test results.
To invoke and use this function, you do the following:
var mathFunction = getMathFunction("-")
println(mathFunction(5,5))
You start by invoking the outer function, passing it a minus sign (
-
), and storing the res-
ults in the
mathFunction
variable. The resulting function is the
subtract()
func-
tion. Once you have a reference to the returned function, you can execute it just like any
other function. Replace the body of
main.swift
with this function and the invocation
code shown previously and run the new code. You will see a
0
printed to the console.
To see the other functions in action, add the following calls to the bottom of
main.swift
and run it once more:
mathFunction = getMathFunction("+")