在嵌套函数中自我捕获

Jaj*_*ris 18 memory-management weak-references nested-function swift capture-list

有了闭包,我通常将[弱自我]附加到我的捕获列表上,然后对self进行空检查:

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

    functionExpectingClosure(myClosure)
}
Run Code Online (Sandbox Code Playgroud)

如果我使用嵌套函数代替闭包,我该如何对self执行null检查(或者检查甚至是必要的......或者使用像这样的嵌套函数甚至是好的做法)即

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

    functionExpectingClosure(nestedFunction)
}
Run Code Online (Sandbox Code Playgroud)

rin*_*aro 27

不幸的是,只有Closures具有"Capture List"功能[weak self].对于嵌套函数,您必须使用法线weakunowned变量.

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

    functionExpectingClosure(nestedFunction)
}
Run Code Online (Sandbox Code Playgroud)

  • 这是官方文件吗? (3认同)