繁体   English   中英

当转义的闭包内的self弱时,在self函数中调用self参数

[英]Invoking a self parameter in a self function when self is weak inside a escaping closure

晚上好。

我开始对在Swift中转义(异步)闭包感到怀疑,我想知道哪种是解决它的最佳方法。

有一个示例函数。

func exampleFunction() {
   functionWithEscapingClosure(onSuccess: { result in
      self.anotherFunction(parameter: self.parameter, result: result)
   }
}

您可能已经注意到,这将导致内存泄漏,因为onSuccess是一个转义的闭包,并且保留了self。

现在,解决问题的方法是在闭包中添加[弱自我]。 而且我希望只有在self不为nil时才调用anotherFunction,所以就像这样:

func exampleFunction() {
   functionWithEscapingClosure(onSuccess: { [weak self] result in
      self?.anotherFunction(parameter: self.parameter, result: result)
   }
}

但是参数是一个问题,因为我不能传递nil参数,所以我必须解开自身才能使用该参数。

使用强制解包( self!.parameter )是否安全,因为该函数仅在self不为nil时才被调用? 我应该在调用self?.parameter之前为self?.parameter执行变量绑定self?.anotherFunction

提前致谢!

是的,你可以写

self?.anotherFunction(parameter: self!.parameter, result: result)

如果selfnil ,则根本不调用该函数。

让我们在捕获列表之后使用它

guard let `self` = self else { return }

您的功能应如下所示:

func exampleFunction() {
   functionWithEscapingClosure(onSuccess: { [weak self] result in
      guard let `self` = self else { return }
      self.anotherFunction(parameter: self.parameter, result: result)
   }
}

因此,不再担心可选(?)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM