gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:18:59 26 4
gpt4 key购买 nike

我收到这个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com