Enum Definition in Swift

Level 3176 keystrokes

Defines an enum with String raw values; printing the case shows its name "north", while rawValue gives "N".

Swift code

// : String makes String the raw value type
1enum Direction: String {
// Each case is given its own raw value
2 case north = "N"
3 case south = "S"
4 case east = "E"
5 case west = "W"
6}
7
// dir has type Direction (inferred)
8let dir = Direction.north
// Printing a case shows its name, not the raw value: Direction: north
9print("Direction: \(dir)")
// rawValue returns the assigned String: Raw: N
10print("Raw: \(dir.rawValue)")

Output

Direction: north
Raw: N
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 12
  • =× 5
  • (× 4
  • )× 4
  • :× 3
  • .× 2
  • \× 2
  • {× 1
  • }× 1

More Swift examples at level 3

← Swift typing practice