Xcode15的 @escaping closure
裡解包後的[weak self]不必再寫 self了!!(好繞口)
用一個範例class Test來實驗,裡面只有一個變數a跟一個testClosure回"test",再用callTestClosure把變數a改成"test"
編譯正常!變數a成功被改成test
同一份code拿到14去編譯,發生錯誤
Reference to property 'a' in closure requires explicit use of 'self' to make capture semantics explicit
在closure裡用到self的東西,一定要標self.XXX
Xcode14/15差在哪?而且一般來說,我們在closure裡寫[weak self],再用self?.a或解包後的self.a是為了避免循環引用。如果Xcode15不必特別寫明self,那他會指向誰?是closure的[weak self]還是外面class的self?🤔
為此特別去搜尋了官方的文件,解答在此!Swift 5.8官方新增了一個改動
self
for weak self
captures, after self
is unwrappedWe should permit implicit self
for weak self
captures, once self
has been unwrapped.
This code would now be allowed to compile:
class ViewController {
let button: Button
func setup() {
button.tapHandler = { [weak self] in
guard let self else { return }
dismiss()
}
}
func dismiss() { ... }
}
要Swift5.8以後才能用(Xcode14↔Swift5.7、Xcode15↔Swift5.9)
解包後的self指的是weak self,以後使用Xcode15解包後的self可以放心大膽的省略了🥰