【问题标题】:Method-overriding from its superclass超类的方法覆盖
【发布时间】:2015-09-29 01:47:26
【问题描述】:

我收到了这个 Swift 错误:

方法不会覆盖其超类中的任何方法!

为什么会出现这个?相关代码如下:

class TouchyView: UIView {

override func touchesBegan(touches: NSSet?, withEvent event: UIEvent) {
    updateTouches(event.allTouches())
}
override func touchesMoved(touches: NSSet?, withEvent event: UIEvent) {
    updateTouches(event.allTouches())
}
override func touchesEnded(touches: NSSet?, withEvent event: UIEvent) {
    updateTouches(event.allTouches())
}
override func touchesCancelled(touches: NSSet!!, withEvent event: UIEvent) {
    updateTouches(event.allTouches())
}

var touchPoints = [CGPoint]()

func updateTouches( touches: NSSet? ) {
    touchPoints = []
    touches?.enumerateObjectsUsingBlock() { (element,stop) in
        if let touch = element as? UITouch {
            switch touch.phase {
                case .Began, .Moved, .Stationary:
                    self.touchPoints.append(touch.locationInView(self))
                default:
                    break
            }
        }
     }
    setNeedsDisplay()
}

【问题讨论】:

标签: swift overriding


【解决方案1】:

继承:如果你有一个带有方法的类

类我的类{

func abc () {
   // do something
}

然后你创建了另一个继承自第一个的类:

class myOtherClass :myClass {

// do whatever stuff in this class

}

第二类也将具有第一类的 abc 方法。 但是,如果您想在第二类中更改 abc 的功能,则必须使用

覆盖

关键字。

class myOtherClass :myClass {

override func abc () {
    // do something else
}


// do whatever stuff in this class

}

swift 让你添加 override 关键字真是太好了,你不会意外地覆盖第一个类中的方法(如果名称非常通用,通常会发生这种情况)。

但是,如果第一类中不存在该方法,则您不能使用覆盖(而且它没有用)。这就是你的情况。

希望这会有所帮助,如果不清楚,我建议您阅读有关面向对象编程的书

【讨论】:

猜你喜欢
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2016-01-02
  • 2015-10-01
  • 1970-01-01
相关资源
最近更新 更多