Game Development Reference
In-Depth Information
Nested Functions
So far all of the functions you have seen defined have been global. Swift makes it possible
to hide functions by nesting them in other functions. Take a look at this function defini-
tion:
func divideAndPrint(num1: Int, num2:Int) {
func divide(num1: Int, num2:Int) ->(quotient : Int,
remainder : Int) {
var quotient = num1 / num2
var remainder = num1 % num2
return (quotient,remainder)
}
var r = divide(num1, num2)
println("\(r.quotient) with a remainder of
: \(r.remainder)")
}
This function, named divideAndPrint() , has another function defined in it named
divide() that takes two Int values and returns a tuple with two labeled Int values.
divide() is visible only inside its encompassing parent, divideAndPrint() . It
cannot be used by any other functions.
To invoke divideAndPrint() , you pass it two Int s. It then invokes the nested di-
vide() function and returns the tuple to the caller. And then the outer function stores the
result in the r variable and prints the tuple values showing the whole-number result of di-
viding the two numbers. Replace the body of main.swift with this code and add a call
to divideAndPrint() , passing values of your choice, directly after the function
definition. You invoked the function with the following call:
divideAndPrint(5, 3)
This invocation resulted in 1, with a remainder of 2.
1 with a remainder of : 2
Functions Returning Functions
Search WWH ::




Custom Search