gpt4 book ai didi

ios - 如何引用非转义闭包?

转载 作者:行者123 更新时间:2023-11-28 05:39:53 25 4
gpt4 key购买 nike

我有以下代码

class Child {
var onClosureFromParent: ((Int) -> Void)?

// Ok.
func setupEscaping(onClosureFromParent: @escaping (Int) -> Void) {
self.onClosureFromParent = onClosureFromParent
}

// Error: Assigning non-escaping parameter 'onClosureFromParent' to an @escaping closure
func setupNonEscaping(onClosureFromParent: (Int) -> Void) {

// FIXME:
self.onClosureFromParent = onClosureFromParent
}
}

我想知道,我怎样才能引用非转义闭包?

最佳答案

来自官方文档:

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

由于函数中的闭包参数,您正在保存它的引用而不是执行它,这意味着该闭包不会在函数范围内执行。因此,您应该让它逃脱。

func setupNonEscaping(onClosureFromParent: (Int) -> Void) {

// Saving the reference, not executing it.
// ie, It will be executed later on...
self.onClosureFromParent = onClosureFromParent

}

代码中的某处...

// The closure is executed later on, thus it should outlive the function lifescope.

let param = 10
self.onClosureFromParent(param)

关于ios - 如何引用非转义闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195801/

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