使用闭包参数分配闭包
Assigning closure with closure parameter
假设我有这个 class
class ClosureTest{
var nestedClosure: (((String) -> Void) -> Void)?
}
如何为 nestedClosure
赋值?
我尝试了下面的代码,但出现错误。有人可以帮忙解释一下吗?
let cTest = ClosureTest()
cTest.nestedClosure = {{ myStr -> Void in } -> Void }
你需要
var nestedClosure:((String) -> Void)?
有
cTest.nestedClosure = { myStr in
}
首先,typealiases 将有助于减少代码中的所有括号:
typealias InnerClosure = ((String) -> Void)
class ClosureTest{
var nestedClosure: ((InnerClosure) -> Void)?
}
当你想给 nestedClosure
赋值时,你需要提供一个闭包,它接受一个 InnerClosure
作为单个参数并且 returns 什么都不接受,因此:
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)
然后输出是:
calling arg from nestedClosure:
the inner closure; txt: called from outer space
或者,没有 innerClosureValue
变量:
cTest.nestedClosure?({ txt in
print ("Or this: \(txt)")
})
暂时删除可选位,(((String) -> Void) -> Void)
是:
- 一个函数...
- 这需要一个函数...
- 需要一个字符串
- 和returns空
- 和returns空
所以一个有用的版本是:
{ f in f("x") }
在此,f
是一个(String) -> Void
。它将传递给闭包,然后闭包将"x"
传递给它。
对于什么都不做的简单版本(如您的示例),代码为:
{ _ in }
意思是“这个闭包接受一个参数并且不对其做任何事情。”
假设我有这个 class
class ClosureTest{
var nestedClosure: (((String) -> Void) -> Void)?
}
如何为 nestedClosure
赋值?
我尝试了下面的代码,但出现错误。有人可以帮忙解释一下吗?
let cTest = ClosureTest()
cTest.nestedClosure = {{ myStr -> Void in } -> Void }
你需要
var nestedClosure:((String) -> Void)?
有
cTest.nestedClosure = { myStr in
}
首先,typealiases 将有助于减少代码中的所有括号:
typealias InnerClosure = ((String) -> Void)
class ClosureTest{
var nestedClosure: ((InnerClosure) -> Void)?
}
当你想给 nestedClosure
赋值时,你需要提供一个闭包,它接受一个 InnerClosure
作为单个参数并且 returns 什么都不接受,因此:
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)
然后输出是:
calling arg from nestedClosure:
the inner closure; txt: called from outer space
或者,没有 innerClosureValue
变量:
cTest.nestedClosure?({ txt in
print ("Or this: \(txt)")
})
暂时删除可选位,(((String) -> Void) -> Void)
是:
- 一个函数...
- 这需要一个函数...
- 需要一个字符串
- 和returns空
- 和returns空
- 这需要一个函数...
所以一个有用的版本是:
{ f in f("x") }
在此,f
是一个(String) -> Void
。它将传递给闭包,然后闭包将"x"
传递给它。
对于什么都不做的简单版本(如您的示例),代码为:
{ _ in }
意思是“这个闭包接受一个参数并且不对其做任何事情。”