Nested Function in Swift with example
Nested Function in Swift
In Swift, a function can exist inside the body of another function is called a nested function. It has the following syntax:
// outer function
func function1() {
// code
// inner function
func function2() {
// code
}
}
Characteristics of Nested Function in Swift
1. Scope: Nested functions are local to the outer function and cannot be called directly from outside of it.
2. Capturing Values: They can access and modify variables and parameters defined in their enclosing function’s scope. This is a form of closure.
3. Encapsulation: They help in encapsulating related logic within a larger function, improving code organization and readability.
Example:
func calculateRectangleProperties(length: Double, width: Double) {
// Nested function to calculate area
func calculateArea() -> Double {
return length * width
}
// Nested function to calculate perimeter
func calculatePerimeter() -> Double {
return 2 * (length + width)
}
let area = calculateArea()
let perimeter = calculatePerimeter()
print("Rectangle with length \(length) and width \(width):")
print("Area: \(area)")
print("Perimeter: \(perimeter)")
}
// Calling the outer function
calculateRectangleProperties(length: 5.0, width: 3.0)