Is self captured within a nested function

人盡茶涼 提交于 2019-12-20 11:38:11

问题


With closures I usually append [weak self] onto my capture list and then do a null check on self:

func myInstanceMethod()
{
    let myClosure =
    {
       [weak self] (result : Bool) in
       if let this = self
       { 
           this.anotherInstanceMethod()
       }
    }   

    functionExpectingClosure(myClosure)
}

How do I perform the null check on self if I'm using a nested function in lieu of a closure (or is the check even necessary...or is it even good practice to use a nested function like this) i.e.

func myInstanceMethod()
{
    func nestedFunction(result : Bool)
    {
        anotherInstanceMethod()
    }

    functionExpectingClosure(nestedFunction)
}

回答1:


Unfortunately, only Closures have "Capture List" feature like [weak self]. For nested functions, You have to use normal weak or unowned variables.

func myInstanceMethod() {
    weak var _self = self
    func nestedFunction(result : Bool) {
        _self?.anotherInstanceMethod()
    }

    functionExpectingClosure(nestedFunction)
}



回答2:


I use this template

class A{

  func foo(){

     func bar(_ this:A){
       this.some();
     }

     bar(self);
  }

  func some(){

  }

}



回答3:


Does not seem to be the case anymore. This is valid in swift 4.1:

class Foo {
    var increment = 0
    func bar() {
        func method1() {
            DispatchQueue.main.async(execute: {
                method2()
            })
        }

        func method2() {
            otherMethod()
            increment += 1
        }
        method1()
    }

    func otherMethod() {

    }
}

The question remains: How is self captured ?



来源:https://stackoverflow.com/questions/26665076/is-self-captured-within-a-nested-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!