我制作一款简单的游戏来更好地了解新语言,我制作了描述游戏等级的枚举。我想制作另一个能够描述每个级别上的敌人的枚举。(级别有不同的敌人)。所以,我想存档这样的东西:
enum GameLevel : Int {
case Forest = 0, Swamp, Castle
...
}
enum Enemies : Int {
// if .Forest than
case Stump = 0, Frog // Forest Enemies
//esle if ...
case Zombie = 0, Witch // Swamp Enemies
case Knight = 0, Archer // Castle Enemies
//var ... some predefined properties that all enemies have but each enemy have it's own values
}
Enemies enum的语法错误,但我正在寻找一种方法来制作这样的东西。存档的最佳解决方案是什么?
答案 0 :(得分:1)
您可以编写一个函数来返回给定级别中的所有敌人,如下所示:
enum GameLevel : Int {
case Forest, Swamp, Castle
}
enum Enemies : Int {
case Stump
case Frog
case Zombie
case Witch
case Knight
case Archer
static func enemiesInLevel(level: GameLevel) -> [Enemies] {
switch level {
case .Forest:
return [Stump, Frog]
case .Castle:
return [Knight, Archer]
default:
return []
}
}
}
// this is how you can call it
let forestEnemies = Enemies.enemiesInLevel(.Forest)
let castleEnemies = Enemies.enemiesInLevel(.Castle)
答案 1 :(得分:1)
您可以向GameLevel添加一个实例方法,列出与GameLevel的特定元素相关的所有敌人。
enum GameLevel : Int {
case Forest = 0, Swamp, Castle
func enemies() -> Array<Enemy> {
switch self {
case .Forest: return [.Stump, .Frog]
case .Swamp: return [.Zombie, .Witch]
case .Castle: return [.Knight, .Archer]
}
}
enum Enemy : Int {
case Stump = 0, Frog, Zombie, Witch, Knight, Archer
}
let forestLevel = GameLevel.Forest
forestLevel.enemies()
最后请注意,Apple建议使用单数名称作为枚举(例如“Enemy”而不是“Enemies”)
每个枚举定义都定义了一种全新的类型。与Swift中的其他类型一样,它们的名称(例如CompassPoint和Planet)应该以大写字母开头。给出枚举类型单数而不是复数名称,以便它们看起来不言而喻:
var directionToHead = CompassPoint.West”
摘自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itunes.apple.com/it/book/swift-programming-language/id881256329?l=en&mt=11