It's possible to have a function within another function, and the inner function can use the variables of the enclosing function. These are called nested functions.
Type in and run the following code:
// Calculating monthly payments for a car loan
func calculateMonthlyPayments(carPrice: Double, downPayment: Double,
interestRate: Double, paymentTerm: Double) -> Double {
// loanAmount() calculates the total loan amount
func loanAmount() -> Double {
return carPrice - downPayment
}
// totalInterest() calculates the total interest amount
incurred for the payment term
func totalInterest() -> Double {
return interestRate * paymentTerm
}
// noOfMonths() calculates the total number of months in
the payment term
func noOfMonths() -> Double {
return paymentTerm * 12
}
return ((loanAmount() + (loanAmount() * totalInterest() / 100))
/ noOfMonths())
}
// calculate monthly payments for a car costing 50,000,
with a downpayment of 5000
// interestRate of 3.5 and 7 years payment term
calculateMonthlyPayments(carPrice: 50000, downPayment: 5000,
interestRate: 3.5, paymentTerm: 7.0)
// result is 666.96
As you can see, there are three functions within calculateMonthlyPayments(carPrice:, downPayment:, interestRate:, paymentTerm:).
The first nested function, loanAmount(), calculates the total loan amount. It returns 50000 - 5000 = 45000.
The second nested function, totalInterest(), calculates the total interest amount incurred for the payment term. It returns 3.5 * 7 = 24.5.
The third nested function, noOfMonths(), calculates the total number of months in the payment term. It returns 7 * 12 = 84. The value returned is ( 45000 + ( 45000 * 24.5 / 100 ) ) / 84 = 666.96, which is the amount you have to pay each month for 7 years to buy this car.
As you can see, functions in Swift are similar to functions in other languages, but they have a cool feature. Functions in Swift are a first-class type, so they can be used as parameters and return types. Let's see how that is done in the next section.