关闭我通常将[weak self]附加到我的捕获列表中,然后对自己执行一个空的检查:
func myInstanceMethod()
{
let myClosure =
{
[weak self] (result : Bool) in
if let this = self
{
this.anotherInstanceMethod()
}
}
functionExpectingClosure(myClosure)
}
如果我使用嵌套函数代替闭包(或者甚至是必要的检查),或者使用这样的嵌套函数甚至是很好的做法,那么我如何执行自检的空检查,即
func myInstanceMethod()
{
func nestedFunction(result : Bool)
{
anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}
不幸的是,只有Closures具有“弱自我”的“捕获列表”功能.对于嵌套函数,必须使用正常的弱或非唯一变量.
func myInstanceMethod() {
weak var _self = self
func nestedFunction(result : Bool) {
_self?.anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}