[英]Swift - Passing closure to method
在距iOS开发2年后,我才开始学习Swift,而且似乎还因为参数语法而陷入僵局。 我在课堂上有以下方法:
func onFollwersButtonTouched(cb: () -> Void) {
self.onFollowingTouchedCb = cb
}
我尝试在另一个类上设置此回调:
cell.onFollowersTouchedCb({ () -> Void in
})
此代码无法编译。 编译器错误是:
Error:(115, 14) cannot convert the expression's type '() -> Void' to type '() -> Void'
而且我不知道发生了什么。 我曾在Apple的Swift书中尝试过这种语法,但同样没有成功。
您应该使用闭包参数调用方法:
cell.onFollowersTouched({ () -> Void in
})
或将闭包分配给变量:
cell.onFollowersTouchedCb = { () -> Void in
}
您当前正在使用闭包参数调用onFollowersTouchedCb
,而没有声明任何参数。
这个:
cell.onFollowersTouchedCb({ () -> Void in
})
没有设置关闭。 您需要执行实际分配:
cell.onFollowersTouchedCb = {
// Do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.