函数嵌套有什么好处(in general/in Swift)

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

我只是在学习一些东西 Swift,我看到了谈论嵌套函数的部分:

Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.

来自here

那么,如果声称的好处是 "organize the code",为什么不在外部函数之外独立地使用嵌套函数呢?对我来说,这似乎更有条理。

我能看出的唯一好处是你 "have access to variables that were declared in the outer function",但与嵌套函数的混乱相比,这似乎微不足道。

有什么想法吗?

So if the purported benefit is to "organize the code", why not just have the nested function independently, outside of the outer function? That, to me, seems more organized.

哦,我完全不同意。如果需要第二个函数的唯一地方是在第一个函数内部,那么将其保留在第一个函数内部更有条理

现实生活中的例子在这里:http://www.apeth.com/swiftBook/ch02.html#_function_in_function

此外,函数中的函数在范围内具有本地环境。嵌套函数内部的代码可以 "see" 在嵌套函数声明之前声明的局部变量。这可比传一堆参数方便自然多了。

但是,key 本地函数可以让您做到而您无法通过任何其他方式轻松做到的事情是,您可以实时形成函数(因为函数是一个闭包)并且 return 它来自外部函数。

http://www.apeth.com/swiftBook/ch02.html#_function_returning_function

IMO,闭包和嵌套函数的唯一区别是递归。您可以在函数体中引用函数本身,无需任何技巧。

func a() {
    func b() {
        b() // Infinite loop!
    }
    b()
}

捕获的引用类型对象在捕获器死亡时死亡。在这种情况下,捕获器是函数的词法范围。这意味着该函数将在完成执行后死亡。

从技术上讲,这会形成一个引用循环,通常不鼓励这样做。但如果你明智地使用它,它会很有用。

例如,将其与异步操作相结合。

func spawnAsyncOp1(_ completion: @escaping () -> Void) {
    enum Continuation {
        case start
        case waitForSomethingElse1
        case retry
        case end
    }
    let someResource = SomeResource()
    func step(_ c: Continuation) {
        switch c {
        case .start:
            return step(.waitForSomethingElse1)

        case .waitForSomethingElse1:
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10), execute: {
                let fc = (someResource.makeRandomResult() % 100 < 50) ? .end : .retry as Continuation
                print("\(fc)")
                return step(fc)
            })

        case .retry:
            return step(.start)

        case .end:
            return completion()
        }
    }
    return step(.start)
}

它可以在没有显式对象实例的情况下使协程执行中的资源管理更简单。资源只是在函数 spawnAsyncOp1 中捕获,并在函数结束时释放。

一件非常好的事情是 Xcode 会在函数弹出窗口中缩进其父函数内的嵌套函数。使用与重新计算布局相关的功能弹出窗口更容易导航,并且所有功能都集中在一个地方。