Swift是一們安全的語言,對于Objective-C中經常出現的block引起的循環引用問題處理的更好,在closure中引用成員屬性的時候,會強制使用self,否則編譯不過。如下代碼:
class TestClass {
var name: String = "aa"
func viewDidLoad() {
testEmbededFunction { () -> () in
name = "bb"
}
}
func testEmbededFunction(f: ()->()) {
f()
}
}
上面的代碼會出現編譯錯誤,提示信息如下:
蘋果官方解釋如下:
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
是因為closure中capture了self,如果self再引用closure的話,就會導致循環引用。因此解決循環引用就有兩種方式:
1、保證closure不會強引用self
2、保證self不會強引用closure
第一種情況的解決辦法:
使用capture list來解決[weak self, unowned self]
第二種情況的解決辦法,
在Swift中可以使用@noescape來保證這一點,比如這樣定義方法就沒事了:
func testEmbededFunction(@noescape f: ()->()) {
f()
}
官方文檔中對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