2014-10-30 24 views
14

帶密封蓋我通常追加[弱自我]到我的捕獲列表,然後做自我空校驗:是自嵌套函數內捕獲

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

    functionExpectingClosure(myClosure) 
} 

如何自我,如果我執行空校驗「M代替封閉的使用嵌套函數(或者甚至是必要的檢查...或者是即使是好的做法是使用一個嵌套函數是這樣),即

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

    functionExpectingClosure(nestedFunction) 
} 

回答

19

遺憾的是,只有瓶蓋有「捕獲列表「功能,如[weak self]。對於嵌套函數,您必須使用正常的weakunowned變量。

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

    functionExpectingClosure(nestedFunction) 
} 
+3

這是在任何機會的官方文件? – 2016-11-02 23:33:39

+0

似乎是這樣。我做了一個測試,閉包中的弱點不會被傳入嵌套函數中的自我。乾淨的代碼非常多。 – possen 2018-01-27 00:11:28