Enums
An enum is a named collection of constants. It desugars to a map literal bound to a name, so members are accessed like map keys.
enum Direction { NORTH, SOUTH, EAST, WEST }
print(Direction.NORTH) # 0print(Direction["SOUTH"]) # 1The desugared form is:
let Direction = {"NORTH": 0, "SOUTH": 1, "EAST": 2, "WEST": 3}Explicit values
Section titled “Explicit values”Members can have explicit values. Integer initializers reset the auto-increment counter.
enum Status { OK, ERROR = 5, TIMEOUT }
print(Status.OK) # 0print(Status.ERROR) # 5print(Status.TIMEOUT) # 6Values do not have to be integers:
enum Token { WORD = "word", NUMBER = "number" }A non-integer initializer stops the counter, so the next member must carry an explicit initializer.
enum Valid { A = "x", B = "y" }
# enum Invalid { A = "x", B } # compile errorAccess
Section titled “Access”Enums are maps, so the usual map operations work.
enum Color { RED, GREEN, BLUE }
print(Color.RED)print(Color["BLUE"])print(Color.keys())print(Color.values())print(Color.has("GREEN"))Because an enum is a map, it is not a distinct runtime type. typeof(Color) is "map".