Skip to content

Traits & Enums

Traits define shared behavior. They replace both interfaces and abstract classes — a trait can have required methods (no body) and default implementations (with a body).

trait Damageable {
func takeDamage(amount: float) // required — must implement
func die() { // default — can override
print("Entity died")
}
}
trait Updatable {
func update(delta: float)
}

Apply traits to a class with with:

class Player extends Entity with Damageable, Updatable {
func takeDamage(amount: float) {
health -= amount
}
func update(delta: float) {
move(delta)
}
// die() inherited from Damageable default
}

Traits can be used as value types for heterogeneous collections:

let units: Array<Damageable> = [player, enemy, boss]
for unit in units {
unit.takeDamage(10.0)
}

Fixed sets of named values. Can be simple labels or carry associated data and methods.

enum Direction { North, South, East, West }
let dir = Direction.North

Variants can carry values. Declare a field and pass values in parentheses:

enum Status {
Alive(100), Wounded(50), Dead(0)
health: int
func isAlive() -> bool {
return health > 0
}
}
let status = Status.Wounded
print(status.isAlive()) // true

Use when to branch on enum variants:

when dir {
is Direction.North => moveNorth()
is Direction.South => moveSouth()
is Direction.East => moveEast()
is Direction.West => moveWest()
}