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

标签 swift closures automatic-ref-counting unowned-references

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

在客户端中,当执行完成处理程序时,我希望有一个 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
      //...
    }
  }
}

最佳答案

正如我在评论中所说

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
 }

关于swift - 将 [unowned self] 添加到闭包参数 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302197/

相关文章:

ios - 相当于只调用一次的 "viewDidLayoutSubviews"?

ios - 保留分配和初始化计数

python - Python 闭包是 `__all__` 的良好替代品吗?

c# - 为什么这个错误是 "local variable cannot be declared in this scope because it ... is already used"?

iphone - 没有调用跟踪的过度释放(使用 ARC),main 中的访问错误

swift - 在涉及 NSHashTable 的特殊情况下不调用 deinit

ios - 使用我的 ios 应用程序 iOS 9 Swift 2.2 中的指示打开 Apple map 应用程序

swift - Xcode 13.3 神奇地将函数调用更改为属性访问

ios - 如何访问 XCUIApplication 中设置的 launchEnvironment 和 launchArguments,在 XCode 中运行 UI 测试?

c# - 可以在闭包中 Lock() 吗?这在 Lambda 和代码输出中是什么样子的?