swift - 从其父类(super class)重写方法

标签 swift overriding

我收到这个 Swift 错误:

Method does not override any method from its superclass!

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

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()
}

最佳答案

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

类我的类{

func abc () {
   // do something
}

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

class myOtherClass :myClass {

// do whatever stuff in this class

}

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

override

关键字。

class myOtherClass :myClass {

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


// do whatever stuff in this class

}

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

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

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

关于swift - 从其父类(super class)重写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32799188/

相关文章:

swift - Xcode 7 中缺少 libsqlite3.dylib 和 libz.dylib。如何使用 Parse?

ios - 我的代码不适用于 TableView 中的部分

c# - 是否可以使抽象方法的参数列表具有可覆盖的长度和类型?

java - 处理一组被覆盖的方法取决于它是任意的还是交替的

java - 如何在java中使用重写的toString()方法

ios - 在 SpriteKit 中出现错误。 - 线程 1 : EXC_BREAKPOINT (code=1, 子代码 = 0x1007351fc)

swift - 使用 ForEach 循环在 Swift 中用不同颜色绘制同心圆

按下NavigationLink时的SwiftUI操作

php - 覆盖在 symfony3 中不起作用的翻译器类

python - Marshmallow:如何覆盖此 Python 类的构造函数?