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

前端 未结 3 1875
天命终不由人
天命终不由人 2020-12-06 03:04

I\'m just learning some Swift and I\'ve come across the section that talks about nesting functions:

Functions can be nested. Nested functions have acc

3条回答
  •  醉梦人生
    2020-12-06 03:51

    IMO, the only difference of closures and nested functions is recursion. You can refer the function itself in the function body without a trick.

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

    Captured reference type object dies when the capturer dies. In this case, capturer is the function's lexical scope. Which means the function is going to die when it finishes its execution.

    Technically, this makes a reference-cycle, and usually discouraged. But this can be useful if you use this wisely.

    For example, combine this with asynchronous operations.

    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)
    }
    

    It can make resource management in a coroutine execution simpler without an explicit object instance. Resources are simply captured in function spawnAsyncOp1 and will be released when the function dies.

提交回复
热议问题