swift - 继承中的枚举

标签 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
    }
}

这当然行不通,我明白

'Actions' is ambiguous for type lookup in this context.

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

最佳答案

这种方法怎么样:

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
    }
}

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

这样您就可以对所有角色一视同仁:询问他们可以执行的操作,这样您就可以显示一个菜单,然后要求角色执行该操作。

我们可以更进一步,使用结构体代替类和枚举的关联值,这是一种更快速的方法,但设置也稍微复杂一些(但更符合逻辑)。

关于swift - 继承中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34495061/

相关文章:

java - 使用 OOPS 扩展已经编写的类

java - 是循环内枚举的开关好风格

ios - 使用 Xcode UI 测试查找 parent 或 sibling

ios - NSDictionary 的第一个元素是 <null> 而不是 1

java - 如何使用不在接口(interface)接口(interface)中的方法 i = new class();

java - 我应该如何使用 Hibernate 从 JPQL 查询中引用内部枚举(在实体中定义)?

java - 泛型不适用于返回类型

ios - 为什么 UDimmingView 总是覆盖屏幕主边界?

pointers - Swift:无法在数组中存储不安全的指针

java - 使用输入文件创建一个对象并将该对象添加到一个数组中,并让它打印出该数组的信息