Swift capture self in closure

Viewed 284

I have the following Swift code:

  func callback(_ status: PHAuthorizationStatus) {

  }

  func myFunction() {

    let handler:(PHAuthorizationStatus) -> Void = { (status) in
         self.callback(status)
     }

      PHPhotoLibrary.requestAuthorization(for: .addOnly) { (status) in
          handler(status)
     }       

  }

What my doubt is whether there is a retain cycle in closures declared as local variable and whether we should use unowned or weak self instead inside handler. How does Swift handle closures declared as local var inside function?

1 Answers

There are two possibilities: Either the function that you call can only call the closure while the function itself is running, then the local variable keeps the closure alive.

Or the function that you call will save the closure away somewhere, and the closure may be called after the function has returned. In that case, the function will declare its closure parameter as "@escaping" and that will keep it alive.

Related