我想在Swift语言中创建一个抽象函数。这是否可行?
class BaseClass {
func abstractFunction() {
// How do I force this function to be overridden?
}
}
class SubClass : BaseClass {
override func abstractFunction() {
// Override
}
}
我想在Swift语言中创建一个抽象函数。这是否可行?
class BaseClass {
func abstractFunction() {
// How do I force this function to be overridden?
}
}
class SubClass : BaseClass {
override func abstractFunction() {
// Override
}
}
我不知道这是否有用,但在尝试构建SpritKit游戏时,我遇到了一个类似的抽象方法问题。我想要一个抽象的Animal类,它具有move()、run()等方法,但是精灵名称(和其他功能)应该由子类提供。所以我最终做了这样的事情(已经测试过Swift 2):
import SpriteKit
// --- Functions that must be implemented by child of Animal
public protocol InheritedAnimal
{
func walkSpriteNames() -> [String]
func runSpriteNames() -> [String]
}
// --- Abstract animal
public class Animal: SKNode
{
private let inheritedAnimal: InheritedAnimal
public init(inheritedAnimal: InheritedAnimal)
{
self.inheritedAnimal = inheritedAnimal
super.init()
}
public required init?(coder aDecoder: NSCoder)
{
fatalError("NSCoding not supported")
}
public func walk()
{
let sprites = inheritedAnimal.walkSpriteNames()
// create animation with walking sprites...
}
public func run()
{
let sprites = inheritedAnimal.runSpriteNames()
// create animation with running sprites
}
}
// --- Sheep
public class SheepAnimal: Animal
{
public required init?(coder aDecoder: NSCoder)
{
fatalError("NSCoding not supported")
}
public required init()
{
super.init(inheritedAnimal: InheritedAnimalImpl())
}
private class InheritedAnimalImpl: InheritedAnimal
{
init() {}
func walkSpriteNames() -> [String]
{
return ["sheep_step_01", "sheep_step_02", "sheep_step_03", "sheep_step_04"]
}
func runSpriteNames() -> [String]
{
return ["sheep_run_01", "sheep_run_02"]
}
}
}