Traits & Enums
Traits
Section titled “Traits”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)}Implementing traits
Section titled “Implementing traits”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 as types
Section titled “Traits as types”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.
Simple enums
Section titled “Simple enums”enum Direction { North, South, East, West }
let dir = Direction.NorthEnums with data
Section titled “Enums with data”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.Woundedprint(status.isAlive()) // truePattern matching
Section titled “Pattern matching”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()}