假设我有这门课
class ClosureTest{
var nestedClosure: (((String) -> Void) -> Void)?
}如何将值赋给nestedClosure
我尝试了下面的代码,但是我得到了一个错误。有人能帮我解释一下吗?
let cTest = ClosureTest()
cTest.nestedClosure = {{ myStr -> Void in } -> Void }发布于 2020-08-27 13:38:18
首先,类型别名有助于减少代码中的所有偏执:
typealias InnerClosure = ((String) -> Void)
class ClosureTest{
var nestedClosure: ((InnerClosure) -> Void)?
}当您想要将一个值释放到nestedClosure时,您需要提供一个闭包,该闭包以一个InnerClosure作为单个参数,而不返回任何内容,因此:
let cTest = ClosureTest()
cTest.nestedClosure = { (arg:InnerClosure) in
print ("calling arg from nestedClosure:")
arg("called from outer space") // call the inner closure
}要使用nestedClosure,您需要提供一个InnerClosure类型的具体值
let innerClosureValue:InnerClosure = { txt in
print ("the inner closure; txt: \(txt)")
}
cTest.nestedClosure?(innerClosureValue)然后,产出是:
从nestedClosure调用arg:
内部封闭;txt:从外层空间调用
或者,不使用innerClosureValue变量:
cTest.nestedClosure?({ txt in
print ("Or this: \(txt)")
})发布于 2020-08-27 13:49:28
将可选位删除一秒钟,(((String) -> Void) -> Void)是:
- And returns Void因此,其中一个有用的版本是:
{ f in f("x") }在这方面,f是一个(String) -> Void。它将被传递给闭包,然后闭包将"x"传递给它。
对于不做任何操作的普通版本(如您的示例中的示例),代码如下:
{ _ in }上面写着“这个闭包只接受一个参数,不会对它做任何事情。”
发布于 2020-08-27 13:11:58
你需要
var nestedClosure:((String) -> Void)?使用
cTest.nestedClosure = { myStr in
}https://stackoverflow.com/questions/63616750
复制相似问题