Functions as Return Types Listing 13.7 vs 12.9


In Listing 12.9 we have:

func(areaOfTriangle(withBase base: Double, andHeight height: Double) -> Double {
let numerator = base * height
func divide() -> Double {
return numerator / 2
return divide ()

and in listing 13.7 we have:

func makeTownGrand() -> (Int, Int) -> Int {
func buildRoads(lightsToAdd: Int, toLights: Int) -> Int {
return toLights + lightsToAdd
return buildRoads

Why in Listing 12.9 we return the nested function with the parentheses, but in 13.7 we don’t include the parentheses when returning the nested function?


The answer is pretty simple, once you understand the fundamental concepts.

Declaration func areaOfTriangle (withBase base: Double, andHeight height: Double) -> Double says that the function returns a value of type Double. That is what return divide () does; it returns the area of a triangle.

Whereas the declaration func makeTownGrand() -> (Int, Int) -> Int says that the function returns a value of type function which takes two Ints as arguments and returns an Int. That is what return buildRoads does; it returns a reference to the inner function which, as the name says, builds roads.


Ok tell me if i got this right please. In Listing 12.9, we are returning the result of the nested function.

But in 13.7 we are only returning the nested function type (as in a reference to this function type)


Yes, and almost yes.

In 13.7, we are returning a pointer to the nested function; we are not returning its type. A type is a compile-time concept, so it can’t be returned as a result.


Thank you! I understand.


Actually, If we want to speak the Swift way… we should say: “we are returning a value of type function”. Pointer word is not allowed :stuck_out_tongue: