Game Development Reference
In-Depth Information
In the previous section, I said a nested function was visible only inside its outer function.
This is correct, but there is a way you can access a nested function. Swift gives you the
ability return a nested function just like any other type. The syntax is just a little different.
When defining a function that returns another function, you have to change the return type
of the returning function to match the parameter list and return the type of the returned
function. This may sound like a mouthful, but it really is pretty straightforward. Take a
look at this function definition:
func getMathFunction(operator: Character) ->(Int, Int)
->Int {
}
This function looks pretty normal to a point. It takes a single Character parameter, but
the return looks a little different. It starts with a normal -> , but after that you see the para-
meter list, (Int, Int) , of the function to be returned followed by the return type of the
function to be returned, Int .
It may be easier to understand this syntax if you put an imaginary function name in the re-
turn definition.
func getMathFunction(operator: Character)
-> imaginaryFunctionName (Int, Int) ->Int {
}
Notice the text imaginaryFunctionName() . If you think about it like this, it looks
like any other function definition.
Note The previous syntax, using a function name in a return type, is only for
clarity purposes. You cannot do this in a real Swift function.
Let's take a look at a real function that returns another function. The function you are go-
ing to create will take a single character representing a simple math operator ( + , - , * , / )
and match the operator to a nested function. When it has a match, it will return the nested
function, and you can use it to perform a math operation. Here is the function:
func getMathFunction(op: Character) ->(Int, Int) ->Int {
func add(num1: Int, num2 :Int) ->Int {
return num1 + num2
Search WWH ::




Custom Search