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