[英]Swift - Passing closure to method
I just started learning Swift after 2 years away from iOS development and I seem to be stuck into the closure as argument syntax. 在距iOS开发2年后,我才开始学习Swift,而且似乎还因为参数语法而陷入僵局。 I have the following method in a class:
我在课堂上有以下方法:
func onFollwersButtonTouched(cb: () -> Void) {
self.onFollowingTouchedCb = cb
}
And I try to set this callback on another class: 我尝试在另一个类上设置此回调:
cell.onFollowersTouchedCb({ () -> Void in
})
This code does not compile. 此代码无法编译。 The compiler error is:
编译器错误是:
Error:(115, 14) cannot convert the expression's type '() -> Void' to type '() -> Void'
And I have no idea what is going on. 而且我不知道发生了什么。 I have tried the syntax on Apple's Swift book but it was unsuccessful as well.
我曾在Apple的Swift书中尝试过这种语法,但同样没有成功。
You should either call method with closure parameter: 您应该使用闭包参数调用方法:
cell.onFollowersTouched({ () -> Void in
})
or assign closure to variable: 或将闭包分配给变量:
cell.onFollowersTouchedCb = { () -> Void in
}
You are currently calling onFollowersTouchedCb
with closure parameter, while has no parameters declared. 您当前正在使用闭包参数调用
onFollowersTouchedCb
,而没有声明任何参数。
This: 这个:
cell.onFollowersTouchedCb({ () -> Void in
})
is not setting the closure. 没有设置关闭。 You need to perform an actual assign:
您需要执行实际分配:
cell.onFollowersTouchedCb = {
// Do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.