我试图实现斯威夫特的替代respondsToSelector:语法,这也显示在主题中。
我有以下几点:
protocol CustomItemTableViewCellDelegate {
func changeCount(sender: UITableViewCell, change: Int)
}然后在后面我调用的代码中
class CustomItemTableViewCell: UITableViewCell {
var delegate: CustomItemTableViewCellDelegate
...
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
...
delegate?.changeCount?(self, change: -1)
}
...
}我得到以下错误
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我做错什么了?
谢谢
发布于 2014-06-10 14:06:36
您有两个?操作符,它们都会导致问题。
首先,在delegate之后的那个表示您想要打开一个可选的值,但是您的delegate属性不是这样声明的。它应该是:
var delegate: CustomItemTableViewCellDelegate?第二,您希望您的changeCount协议方法是可选的。如果需要,则需要使用@objc属性标记协议,并用optional属性标记函数:
@objc protocol CustomItemTableViewCellDelegate {
optional func changeCount(sender: UITableViewCell, change: Int)
}(注释:符合@objc协议的类需要是@objc本身。在本例中,您将对Objective类进行子类化,因此您将被覆盖,但是需要用@objc属性标记一个新类。)
如果您只希望委托是可选的(也就是说,没有委托是可以的,但所有委托都需要实现changeCount),那么保持原样,并将该方法调用更改为:
delegate?.changeCount(self, change: -1)发布于 2014-06-10 14:00:53
错误说明了一切。
在显式类型上使用?,它不能是nil,所以简单地说,不要在该变量上使用?。
如果你有一个像这样的变量
var changeCount: Int或者这个
var changeCount = 3你有一个明确的类型。当请求显式类型时,您应该给出一个显式类型,即changeCount,而不是changeCount?。
如果您希望开始使用可选变量,请使用?声明它。
var changeCount: Int?如果类型应该是隐式的,则不能在可选类型中使用文字语法。因为3总是显式的,如果没有说明的话。
https://stackoverflow.com/questions/24142906
复制相似问题