Swift语言中的抽象函数

148

我想在Swift语言中创建一个抽象函数。这是否可行?

class BaseClass {
    func abstractFunction() {
        // How do I force this function to be overridden?
    }
}

class SubClass : BaseClass {
    override func abstractFunction() {
        // Override
    }
}

这与您的另一个问题非常接近(https://dev59.com/BWAf5IYBdhLWcg3w9Wmu),但这里的答案似乎更好。 - David Berry
这些问题可能相似,但解决方案却大不相同,因为抽象类与抽象函数有着不同的用例。 - kev
是的,我为什么没有投票关闭呢,但那里的答案除了“你不能”之外就没有用处了。在这里,您得到了最好的可用答案 :) - David Berry
已解决。请参考此链接:https://stackoverflow.com/a/65816990/294884 - undefined
11个回答

1

我不知道这是否有用,但在尝试构建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"]
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接