gpt4 book ai didi

swift - 如何以参数作为参数传递闭包并执行它?

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:58 24 4
gpt4 key购买 nike

A 类的初始化器接受一个可选的闭包作为参数:

class A {
var closure: ()?

init(closure: closure()?) {
self.closure = closure
self.closure()
}
}

我想传递一个带有参数的函数作为闭包:

class B {
let a = A(closure: action(1)) // This throws the error: Cannot convert value of type '()' to expected argument type '(() -> Void)?'

func action(_ i: Int) {
//...
}
}

A 应该执行带有参数 i 的闭包 action

我不确定如何正确编写此代码,请参阅上面代码注释中的错误。必须更改什么?

最佳答案

请确保您的“what-you-have-now”代码没有错误。

假设你的类 A 是这样的:

class A {
typealias ClosureType = ()->Void

var closure: ClosureType?

init(closure: ClosureType?) {
self.closure = closure
//`closure` would be used later.
}

//To use the closure in class A
func someMethod() {
//call the closure
self.closure?()
}
}

使用上面给出的A,您需要将类B重写为:

class B {
private(set) var a: A!
init() {
//initialize all instance properties till here
a = A(closure: {[weak self] in self?.action(1)})
}

func action(i: Int) {
//...
}
}

关于swift - 如何以参数作为参数传递闭包并执行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38338765/

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