我试图实现swift替代respondsToSelector:语法的替代方法,该语法也在主题演讲中展示.
我有以下内容:
protocol CustomItemTableViewCellDelegate {
func changeCount(sender: UITableViewCell, change: Int)
}
Run Code Online (Sandbox Code Playgroud)
然后在我调用的代码中
class CustomItemTableViewCell: UITableViewCell {
var delegate: CustomItemTableViewCellDelegate
...
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
...
delegate?.changeCount?(self, change: -1)
}
...
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Operand of postfix '?' should have optional type; type is
'(UITableViewCell, change:Int) -> ()'Operand of postfix '?' should
have optional type; type is 'CustomItemTableViewCellDelegate'Partial application of protocol method is not allowed我做错了什么?
谢谢
你有两个?操作员,他们都造成了问题.
首先,后面的delegate那个表示你要打开一个可选值,但你的delegate属性没有这样声明.它应该是:
var delegate: CustomItemTableViewCellDelegate?
Run Code Online (Sandbox Code Playgroud)
其次,看起来你希望你的changeCount协议方法是可选的.如果这样做,则需要使用@objc属性标记协议并使用属性标记函数optional:
@objc protocol CustomItemTableViewCellDelegate {
optional func changeCount(sender: UITableViewCell, change: Int)
}
Run Code Online (Sandbox Code Playgroud)
(注意:符合@objc协议的类必须是@objc它们自己.在这种情况下,你是子类化Objective-C类,所以你被覆盖了,但是新类需要用@objc属性标记.)
如果您只希望委托是可选的(也就是说,没有代理,但是所有委托都需要实现changeCount),那么保持协议不变并将该方法调用更改为:
delegate?.changeCount(self, change: -1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10783 次 |
| 最近记录: |