gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:33:15 26 4
gpt4 key购买 nike

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com