What is the practical use of nested functions in swift?


This question already has an answer here:

  • What is the benefit of nesting functions (in general/in Swift) 2 answers

What is the practical use of nested functions? It only makes the code harder to read and doesn't make a particular case easy.

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backwards ? stepBackward : stepForward


I think the core of your question is: Why not use private function instead of an ugly nested function?

Simply put, nested functions can bring more readability and encapsulation

A private function can still be accessed from other functions in your class. The same isn't true for nested functions. You're telling your developers, this only belongs to this function ( contrary to private functions where they belong to the entire class). Back off and don't mess with it, if you need similar capability, go write your own!

Another convenience is that it can access all the local parameters to its parent function. You no longer need to pass them around. This would eventually mean one less function to test, because you've wrapped one function inside another

Another use case would be when you have very similar functions in your class, say like you have:

extractAllHebrewNames() // right to left language
extractAllAmericanNames() // left to right language
extractAllJapaneseNames() // top to bottom language

Now if you have a private func named printName (that prints names), it would work if you switch the case based on language, but what if just you don't/can't do that. Instead you can write your own nested functions* inside each separate extract function and print the names.

Your question is somewhat similar, to why not use 'if else' instead of a 'Switch case.

I think it's just a convenience provided (for something that can be dealt without using nested functions).

*: They could all now have the exact same name. because each is in a different namespace.