将 [unowned self] 添加到闭包参数 Swift

Add [unowned self] to the closure argument Swift

我有一个带有完成处理程序的函数,返回一个或多个参数。

在客户端中,当执行完成处理程序时,我希望有一个 unownedself 的引用,以及对传递的参数的访问权。

这里是 Playground 示例,说明了问题和我要实现的目标。

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
      //...
    }
  }
}

你需要的只是在闭包参数列表中包含 [unowned self] 的语法吗?

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

class Class {
    func execute() {
        Struct().function { [unowned self] string in
            print(string)
            print(self)
        }
    }
}

Class().execute()

正如我在评论中所说

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

捕获列表闭包参数应该是闭包中的顺序更多信息来自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
 }