 # Nested functions

Hey guys. I am going through apple swift book.

Could anyone please explain to me why we do need to assign second function into variable to make it work? Why can we not call it `makeIncrementer(7)` ?
Any help appreciated, thanks.

The function `makeIncrementer` has the following type signature:

``````() -> ((Int) -> Int)
``````

This means that it accepts no arguments and returns a function of type `(Int) -> Int`.

``````var increment = makeIncrementer()
``````

is then a function that accepts an `Int` and returns an `Int`.

1 Like

okay, thank you. What would happen if you had function in function in function (3) and the last function would be the one that accepts the argument?

Depending on what you mean by "function in function" it can have different results.

Take a look at the following type signatures:

``````typealias Type1 = (Double) -> ((Double) -> Double)
typealias Type2 = ((Double) -> Double) -> Double
``````

In the first case you have a function that accepts a `Double` as argument and returns something of type `(Double) -> Double`, i.e. a function that accepts a `Double` and returns a `Double`.
An example of such function may be:

``````import Foundation

func makeRootFunction(degree: Double) -> ((Double) -> Double) {
func root(value: Double) -> Double {
return pow(value, 1 / degree)
}
return root  // root is of type (Double) -> Double
}

let squareRoot = makeRootFunction(degree: 2)
let cubeRoot = makeRootFunction(degree: 3)

squareRoot(25)  // returns 5.0
cubeRoot(27)    // returns 3.0
``````

In the second case you have a function that accepts an argument of type `(Double) -> Double`, i.e. a function, and returns a `Double`.

I'm assuming you're referring to a type signature like the following one:

``````typealias Type3 = (Int) -> ((Int) -> ((Int) -> Int))
``````

which can also be written as

``````typealias Type3 = (Int) -> (Int) -> (Int) -> Int
``````

In this case you have a function that accepts an `Int` and returns a function of type `(Int) -> (Int) -> Int`, i.e. a function like that accepts an `Int` and returns a function of type `(Int) -> Int`.

``````func f(_ a: Int) -> (Int) -> (Int) -> Int { ... }

f(3)        // is of type (Int) -> (Int) -> Int
f(3)(7)     // is of type (Int) -> Int
f(3)(7)(2)  // is of type Int
``````
3 Likes