swiftclosuresautomatic-ref-countingunowned-references

Add [unowned self] to the closure argument Swift


I have a function with a completion handler, returning one parameter or more.

In a client, when executing a completion handler, I'd like to have an unowned reference to self, as well as having access to the parameter passed.

Here is the Playground example illustrating the issue and the goal I'm trying to achieve.

import UIKit

struct Struct {
  func function(completion: (String) -> ()) {
    completion("Boom!")
  }

  func noArgumentsFunction(completion: () -> Void) {
    completion()
  }
}

class Class2 {
  func execute() {
    Struct().noArgumentsFunction { [unowned self] in
      //...
    }

    Struct().function { (string) in // Need [unowned self] here
      //...
    }
  }
}

Solution

  • As I said in my comment

    Struct().function { [unowned self] (string) in 
        //your code here 
    }
    

    Capture list and closure parameters that should be the order in closures more info from Apple Documentation

    Defining a Capture List

    Each item in a capture list is a pairing of the weak or unowned keyword with a reference to a class instance (such as self) or a variable initialized with some value (such as delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.

    Place the capture list before a closure’s parameter list and return type if they are provided:

    lazy var someClosure: (Int, String) -> String = {
        [unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
        // closure body goes here 
    }
    

    If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in keyword:

    lazy var someClosure: () -> String = {
         [unowned self, weak delegate = self.delegate!] in
         // closure body goes here
     }