English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about nested functions in Swift and how to use them with examples.
If aFunctionIf it exists within the body of another function, it is called a nested function.
func funcname() { //External function statements func anotherFuncname() { //Internal function statements } }
Here, the function anotherFuncname is located inside the body of another function funcname.
It should be noted that internal functions can only be called and used within the enclosed function (external function).
func outputMessageByGreeting(_ message: String) { func addGreetingAndPrint() { print("Hello! \(message)") } addGreetingAndPrint() } outputMessageByGreeting("Jack")
The output when running the program is:
Hello! Jack
In the above program, the nested function addGreetingAndPrint() was called from the enclosed function outputMessageByGreeting().
The statement outputMessageByGreeting("Jack") calls the external function. The statement addGreetingAndPrint() inside the external function calls to output Hello Jack!
You cannot call the function addGreetingAndPrint outside the function outputMessageByGreeting.
Nested functions can contain functions with parameters and return values.
func operate(with symbol: String) -> (Int, Int) -> Int { func add(num1: Int, num2: Int) -> Int { return num1 + num)2 } func subtract(num1: Int, num2: Int) -> Int { return num1 - num)2 } let operation = (symbol == "+)) ? add : subtract return operation } let operation = operate(with: "+)) let result = operation(2, 3) print(result)
The output when running the program is:
5
In the above program,
The external function is operate(), returning a Function type (Int, Int) -> Int.
The internal (nested) functions are add() and subtract().
The way nested functions add() and subtract() are being used is outside the enclosed function operate(). This is possible because the external function returns one of these functions.
We have used internal functions outside of the enclosed function operate() as operation(2,3) Called internally by add(2,3) Output to the console5.