Swift是一們安全的語言,對(duì)于Objective-C中經(jīng)常出現(xiàn)的block引起的循環(huán)引用問題處理的更好,在closure中引用成員屬性的時(shí)候,會(huì)強(qiáng)制使用self,否則編譯不過。如下代碼:
class TestClass {
var name: String = "aa"
func viewDidLoad() {
testEmbededFunction { () -> () in
name = "bb"
}
}
func testEmbededFunction(f: ()->()) {
f()
}
}
上面的代碼會(huì)出現(xiàn)編譯錯(cuò)誤,提示信息如下:

蘋果官方解釋如下:
Swift requires you to write self.someProperty or self.someMethod() (rather than just someProperty or someMethod()) whenever you refer to a member of self within a closure. This helps you remember that it's possible to capture self by accident
是因?yàn)閏losure中capture了self,如果self再引用closure的話,就會(huì)導(dǎo)致循環(huán)引用。因此解決循環(huán)引用就有兩種方式:
1、保證closure不會(huì)強(qiáng)引用self
2、保證self不會(huì)強(qiáng)引用closure
第一種情況的解決辦法:
使用capture list來解決[weak self, unowned self]
第二種情況的解決辦法,
在Swift中可以使用@noescape來保證這一點(diǎn),比如這樣定義方法就沒事了:
func testEmbededFunction(@noescape f: ()->()) {
f()
}
官方文檔中對(duì)noescape的描述:
Apply this attribute to a function or method declaration to indicate that a parameter it will not be stored for later execution, such that it is guaranteed not to outlive the lifetime of the call. Function type parameters with the noescape declaration attribute do not require explicit of self. for properties or method