我想要创建一个处理闭包的方法。闭包包含方法调用,我的闭包方法应该按顺序执行它们,例如:
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()
}
}这会导致错误:
不能将类型'(_) -> _‘的值转换为预期的参数类型'(() -> Bool)?’
我不明白在闭包参数中需要定义什么类型才能起作用。
此外,我希望消除闭包中的self.引用,以便它能够与以下内容一起工作:
when("I tap the Get Coffee button")
{
_ in
tap(p.button1)
wait(1)
tap(p.button1)
return true
}发布于 2017-10-11 06:16:35
删除_ in。这告诉编译器闭包有一个参数,但是您的闭包是() -> Bool,也就是说,没有参数。
至于删除self,您必须使闭包不可转义。所有可选闭包都是@escaping,因此闭包必须是非可选的:
public func when(_ name:String, closure:(() -> Bool)) {
_ = closure()
}
when("I tap the Get Coffee button") {
tap(p.button1)
wait(1)
tap(p.button1)
return true
}转义闭包可以创建所有权周期(内存泄漏),这就是为什么self (self将被捕获)的每次使用都必须是显式的。
发布于 2017-10-11 06:22:13
我想我能得到你想要的。不过,我可能错了。
由于您想使用tap和wait而不使用self,所以需要在闭包的参数列表中使用它们。
tap的签名似乎是(UIButton) -> (),wait的签名似乎是(Int) -> ()。
因此,将这两个闭包传递给闭包。
由于类型变得非常复杂,我建议您使用类型别名:
typealias WhenHandler = ((UIButton) -> (), (Int) -> ()) -> Bool您的when方法可以是:
public func when(_ name:String, closure: WhenHandler)应该将self.tap和self.wait传递给when方法中的closure,如下所示:
if let c = closure
{
_ = c(self.tap, self.wait)
}现在,您可以这样调用when:
when("I tap the Get Coffee button")
{
tap, wait in
tap(p.button1)
wait(1)
tap(p.button1)
return true
}https://stackoverflow.com/questions/46680970
复制相似问题