枚举继承

时间:2015-12-28 14:07:37

标签: swift oop enums

我有一个派生自一个基类的多个类,其中的多态方法接受基类中声明的枚举类型。我在子类中重复枚举,以便每个子类只接受自己特定的值组:

class Character {

    enum Actions {

    }

    func performAction(action: Actions) {
        // Functions to be performed by all subclasses
    }
}


class Warrior: Character {

    enum Actions {
        case Attack, Block, Charge
    }

    override func performAction(action: Actions) {
        // Add subclass-specific behavior
    }
}

class Wizard: Character {

    enum Actions {
        case Attack, CastSpell, Run
    }

    override func performAction(action: Actions) {
        // Add subclass-specific behavior
    }
}

这当然不起作用我得到

  

'动作'在此上下文中对于类型查找是不明确的。

我无法删除基类中的枚举,因为我得到了该方法未声明的类型错误。我有一种强烈的感觉,我认为这一切都错了,并试图重新发明轮子。有人能指出我正确的方向吗?谢谢。

1 个答案:

答案 0 :(得分:1)

这种方法怎么样:

enum Action {
    case Attack, Block, Charge, CastSpell, Run
}

class Character {

    final func performAction(action: Action) {
        if self.allowedActions().contains(action) {
            self.executeAction(action);
        }
    }

    func allowedActions() -> [Action] {
        // to be overriden in subclasses
        return []
    }

    func executeAction(action: Action) {
        // this will also be overriden in subclasses
    }
}

class Warrior: Character {
    override func allowedActions() -> [Action] {
        return [.Attack, .Block, .Charge]
    }

    override func executeAction(action: Action) {
        // do whatever is needed
    }
}

class Wizard: Character {
    override func allowedActions() -> [Action] {
        return [.Attack, .CastSpell, .Run]
    }

    override func executeAction(action: Action) {
        // do whatever is needed
    }
}

使用一个枚举来保存所有可能的操作,并为每个子类定义允许哪些操作。

通过这种方式,您可以将所有字符视为相同:询问他们可以执行的操作,以便您可以显示菜单,然后让角色执行该操作。

我们可以更进一步,通过使用结构而不是枚举的类和相关值,这是一种更加快速的方法,但设置也有点复杂(但更合乎逻辑)。