【发布时间】:2017-10-11 06:11:22
【问题描述】:
我想创建一个处理闭包的方法。闭包包含方法调用,我的闭包方法应该按顺序执行它们,例如:
when("I tap the Get Coffee button")
{
_ in
self.tap(p.button1)
self.wait(1)
self.tap(p.button1)
return true
}
还有我的(简化的)闭包方法:
public func when(_ name:String, closure:(() -> Bool)? = nil)
{
if let c = closure
{
_ = c()
}
}
这会导致错误:
无法将 '(_) -> _' 类型的值转换为预期的参数类型 '(() -> 布尔)?'
我不明白需要在闭包参数中定义什么类型才能使其工作。
另外,我想消除闭包中的 self. 引用,以便它与:
when("I tap the Get Coffee button")
{
_ in
tap(p.button1)
wait(1)
tap(p.button1)
return true
}
【问题讨论】:
-
将闭包设为可选有什么意义?你会在没有闭包的情况下调用
when方法吗? -
如果你只是忽略返回值,为什么还要定义一个返回类型为
Bool的闭包呢? -
@maddy 这两个都有原因,因此我写了(简化)。