swiftmemory-managementweak-referencesnested-functioncapture-list

Is self captured within a nested function


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

Solution

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