Javatpoint Logo
Javatpoint Logo

Swift Nested Function

A function inside the body of another function is called nested function.

Syntax:

Parameter Explanation:

Here, function1 is an outer function because there is another function named function2 (nested function) inside the function1.

Note: The inner function can only be called and used inside the outer function.

Nested Function without Return Values

Output:

Good Morning! Ajeet

In the above program, the nested function wish2() is being called from the outerfunction wish1().

The statement wish1("Ajeet") calls the outer function and the statement wish2 () inside the outer function calls the method which gives the output Good Morning Ajeet.

You cannot call the function wish2 outside of the function wish1.

Nested function with parameters and Return value

The nested functions can also contain parameters and return values.

Example:

Output:

30

In the above program,

  • The outer function is operate(), with return value of type Function (Int,Int) -> Int.
  • The inner (nested) functions are add() and subtract().

The nested function add() and subtract() in a way are being used outside of the enclosing function operate(). This is possible because the outer function returns one of these functions.

We've used the inner function outside the enclosing function operate() as operation(10, 20). The program internally calls add(10, 20) which provides an output 30.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA