如何解决用闭包参数分配闭包
假设我有这个课程
class ClosureTest{
var nestedClosure: (((String) -> Void) -> Void)?
}
如何为nestedClosure
分配值?
我尝试了以下代码,但出现错误。有人可以帮忙解释一下吗?
let cTest = ClosureTest()
cTest.nestedClosure = {{ myStr -> Void in } -> Void }
解决方法
首先,类型别名将有助于减少代码中的所有括号:
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)")
})
,
将可选位(((String) -> Void) -> Void)
拖放一秒钟是
- 一个功能...
- 需要一个功能...
- 需要一个字符串
- 并返回Void
- 并返回Void
- 需要一个功能...
因此,一个有用的版本是:
{ f in f("x") }
在此,f
是(String) -> Void
。它将被传递到闭包,然后闭包将"x"
传递给它。
对于不执行任何操作的普通版本(例如您的示例),代码将是:
{ _ in }
这表示“此闭包采用一个参数,对此不执行任何操作。”
,您需要
var nestedClosure:((String) -> Void)?
使用
cTest.nestedClosure = { myStr in
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。