对于闭包,我通常将 [weak self]
附加到我的捕获列表中,然后对 self
进行空检查:
func myInstanceMethod()
{
let myClosure =
{
[weak self] (result : Bool) in
if let this = self
{
this.anotherInstanceMethod()
}
}
functionExpectingClosure(myClosure)
}
如果我使用嵌套函数代替闭包,我该如何对 self
执行 null 检查(或者检查是否必要......或者使用像这样的嵌套函数)即
func myInstanceMethod()
{
func nestedFunction(result : Bool)
{
anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}
最佳答案
不幸的是,只有闭包有像[weak self]
这样的“捕获列表”特性。对于嵌套函数,您必须使用普通的 weak
或 unowned
变量。
func myInstanceMethod() {
weak var _self = self
func nestedFunction(result : Bool) {
_self?.anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}
关于swift - 在嵌套函数中 self 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665076/