简体   繁体   中英

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

Good evening.

I come bearing a doubt about escaping (asynchronous) closures in Swift, and I'd want to know which would be the best way to solve it.

There's an example function.

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

As you've probably noticed, this will cause a memory leak, since onSuccess is an escaping closure and it's retaining self.

Now, the way to solve it is adding [weak self] in the closure. And I want anotherFunction to be invoked only if self isn't nil, so it would be like that:

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

But the parameter is an issue, since I can't pass on a nil parameter, I have to unwrap self to use the parameter.

Would it be safe to use a force unwrap ( self!.parameter ), since the function only gets called if self is not nil? Should I perform a variable binding for self?.parameter before calling self?.anotherFunction ?

Thanks in advance!

Yes, you can write

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

If self is nil the function isn't called at all.

Let's use this after your capture list

guard let `self` = self else { return }

Your function should be like this:

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

So, dont worry about the optional (?) anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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