gpt4 book ai didi

Swift:实例方法作为闭包不起作用

转载 作者:行者123 更新时间:2023-11-30 11:02:08 25 4
gpt4 key购买 nike

var closureA: (String)->()

class Test {
func instanceMethod(string: String) {
}
}

let a = Test()

closureA = Test.instanceMethod(a)

closureA("hello")

Xcode10 Playground 显示错误:

错误:无法将“(String) -> ()”类型的值分配给“(String) -> ()”类型闭包A = Test.instanceMethod(a)

我已经读过:https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/

最佳答案

我认为你错过了闭包的要点,你不能将函数存储在闭包中,但你可以将调用函数的代码与传递到闭包中的变量和函数一起存储仍然需要一个类实例来调用它,所以它应该是这样的:

var closureA: ((String)->())?

class Test {
func instanceMethod(string: String) {
print(string)
}
}

let a = Test()

//Assume you have a variable `str: String` before hand that will execute the code inside closure
closureA = { str in
a.instanceMethod(string: str)
}

//Actual call to the closure to execute it
closureA?("hello")

关于Swift:实例方法作为闭包不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53219718/

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