替换为respondsToSelector的Swift:

时间:2014-06-10 13:56:09

标签: swift

我试图实现swift的替代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

我做错了什么?

由于

2 个答案:

答案 0 :(得分:9)

您有两个?运算符,它们都会导致问题。

首先,delegate之后的那个表示您想要解包一个可选值,但是delegate属性没有这样声明。它应该是:

var delegate: CustomItemTableViewCellDelegate?

其次,看起来您希望changeCount协议方法是可选的。如果这样做,则需要使用@objc属性标记协议,并使用optional属性标记该函数:

@objc protocol CustomItemTableViewCellDelegate {
    optional func changeCount(sender: UITableViewCell, change: Int)
}

注意:符合@objc协议的类本身需要@objc。在这种情况下,你是一个Objective-C类的子类,所以你是已覆盖,但新类需要使用@objc属性进行标记。)

如果您只希望委托是可选的(也就是说,没有委托可以,但是所有委托都需要实现changeCount),那么请按原样保留协议,并将该方法调用更改为:

delegate?.changeCount(self, change: -1)

答案 1 :(得分:0)

错误说明了一切。

您在显式类型上使用?,它不能是nil,因此请勿在该变量上使用?

如果你有像这样的var

var changeCount: Int

或者

var changeCount = 3

您有一个明确的类型。当请求显式类型时,您应该提供一个显式类型,changeCount而不是changeCount?

如果您想要开始使用可选变量,请使用?声明它:

var changeCount: Int?

如果类型应该是隐式的,则不能将文字语法与可选类型一起使用。因为如果没有另外说明,3总是显式为Int。

相关问题