What is the practical use of nested functions in swift?

4 Solutions Collect From Internet About “What is the practical use of nested functions in swift?”

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.

One use case is operations on recursive data structures.

Consider, for instance, this code for searching in binary search trees:

func get(_ key: Key) -> Value? {
    func recursiveGet(cur: Node) -> Value? {
        if cur.key == key {
            return cur.val
        } else if key < cur.key {
            return cur.left != nil ? recursiveGet(cur: cur.left!) : nil
        } else {
            return cur.right != nil ? recursiveGet(cur: cur.right!) : nil
        }
    }

    if let root = self.root {
        return recursiveGet(cur: root)
    } else {
        return nil
    }
}

Of course, you can transform the recursion into a loop, doing away with the nested function. I find recursive code often clearer than iterative variants, though. (Trade off vs. runtime cost!)

You could also define recursiveGet as (private) member outside of get but that would be bad design (unless recursiveGet is used in multiple methods).

In your example, you can create a variable which is also a function like this:

var myStepFunction = chooseStepFunction(true)

myStepFunction(4)

The benefit of nested function is really nice. For example, let’s say you are building an app for the calculator, you can have all your logic in one function, as the following:

func doOperation(operation: String) -> ((Double, Double) -> Double)? {
    func plus(s: Double, d: Double) -> Double {
        return s + d
    }
    func min(s: Double, d: Double) -> Double{
        return s - d
    }
    switch operation {
        case "+":
            return plus
    case "-" :
        return min
    default :
        return nil
    }
}

var myOperationFunction = doOperation("-")?(4, 4) // 0
var myOperationFunction2 = doOperation("+")?(4, 5) //9

In some cases, you are not allowed to see the implementation of some function, or not responsible for them. Then hidding them inside other function is really a good approach. For instance, assume that you colleague is reaponsible for developing the plus and min functions, he/she will do that, and you just use the outer function.

It is deferent from closure, because in clouser, you pass your logic to other logic, which will call yours. It is kind of plugin. For instance, after calling the http request, you can pass the code that you want your app to do when receiving the response from the server

There is the principle (since Objective-C) that “code can be data”. You can pass code around, store it in a variable, combine it with other code. This is an extremely powerful tool. Frankly, if I didn’t have the ability to treat code as data, most of the code I write would be ten times harder to write, and ten times harder to read.

Functions in Swift are just closures, so nested functions make perfectly sense, since this is how you write a closure when you don’t want to use one of the many available shortcuts.