简体   繁体   English

在闭包参数Swift中添加[unown self]

[英]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. 在客户端中,当执行完成处理程序时,我想unownedselfunowned引用,以及对传递的参数的访问权。

Here is the Playground example illustrating the issue and the goal I'm trying to achieve. 这是一个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
      //...
    }
  }
}

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 捕获应该是关闭顺序的列表关闭参数 ,详情请参阅Apple文档

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!). 捕获列表中的每个项目都是对weak或unown关键字的配对,这些关键字与对类实例的引用(例如self)或用某个值初始化的变量(例如委托= 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: 如果闭包没有指定参数列表或返回类型,因为可以从上下文中推断出它们,则将捕获列表放在闭包的最开始,然后是in关键字:

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

Is it just the syntax for including [unowned self] in the closure parameter list you need? 仅仅是将[unown 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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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