我遇到了在超类中定义的函数无法正常工作的问题。经过一些调查后发现,超类中定义的变量在子类中不起作用,尽管代码提示识别它并且代码正在运行,并且在经过大量的摆弄之后我完全陷入困境:
class Super {
//records absolute time of last frame
var timeThen: Double = 0
func getElapsedTime () -> CGFloat {
//records current time
let timeNow = CFAbsoluteTimeGetCurrent()
//finds duration since last update
let duration = timeNow-timeThen
//resets timeThen to current time for next run
timeThen = timeNow
//casts Double value to CGFloat and returns
return CGFloat(duration)
}
init () {
timeThen = CFAbsoluteTimeGetCurrent()
}
}
子类如下:
class Sub: Super {
//gets time from function but doesn't work and seems to run incredibly slowly
let timeElapsed = getElapsedTime()
//run code based on interval
}
所以我尝试手动完成:
class Sub: Super {
//still doesn't work
let timeNow = CFAbsoluteTimeGetCurrent()
let timeElapsed = CGFloat(timeNow-timeThen)
timeThen = timeNow
//run code based on interval
}
但是,如果我使用子类中定义的变量,它的完美运作:
class Sub: Super {
//new variable to replace 'faulty' one
var timeThen2: Double = 0
// Now it works
let timeNow = CFAbsoluteTimeGetCurrent()
let timeElapsed = CGFloat(timeNow-timeThen2)
timeThen2 = timeNow
// run code based on interval
}
有什么想法吗?
非常感谢, 千瓦