对于闭包,我通常会附加[weak self]
到我的捕获列表,然后进行空检查self
:
func myInstanceMethod()
{
let myClosure =
{
[weak self] (result : Bool) in
if let this = self
{
this.anotherInstanceMethod()
}
}
functionExpectingClosure(myClosure)
}
如何执行空检查self
如果我使用嵌套函数代替闭包(或者检查是否必要……或者使用这样的嵌套函数是否是一个好的做法),即
func myInstanceMethod()
{
func nestedFunction(result : Bool)
{
anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}
不幸的是,只有闭包具有“捕获列表”功能,例如[weak self]
。对于嵌套函数,您必须使用普通weak
or unowned
变量。
func myInstanceMethod() {
weak var _self = self
func nestedFunction(result : Bool) {
_self?.anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)