簡體   English   中英

Swift閉包中的`self`

[英]`self` in Swift closure

我想在Swift閉包中理解self 對於前 -

() -> Void = { [weak self] in
    guard let `self` = self else { 
        self.callMethod2()
    }
    self.callMethod3()
}

為什么我們在這里使用反擊? 這是很好的編程習慣嗎? 如何在這里弱勢地捕捉到自我?

Swift 4.2最近采納了一項建議,將其添加到語言中:

guard let self = self else { return }

建議的解決方案需要允許self使用可選綁定從弱引用升級到強引用。

有關更多詳細信息,請參閱swift evolution proposal SE-0079

self是斯威夫特的一個保留詞。 由於您正在創建一個名為self的新本地var,因此您需要使用反向標記對其進行標記,如rmaddy中的鏈接所述。

請注意,將弱self映射到強var的通常約定是使用名稱strongSelf

() -> Void = { [weak self] in
    guard let strongSelf = self else { 
        //your code to call self.callMethod2() can't succeed inside the guard (since in that case weak self is nil)
        //self.callMethod2()
        return   //You must have a statement like return, break, fatalEror, or continue that breaks the flow of control if the guard statement fails
    }
    strongSelf.callMethod3()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM