Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Raw Values in Swift Enumerations
Written by Team Kodeco

Enumerations in Swift can be assigned specific values known as raw values. These raw values can be of any basic data types such as integers, strings or characters. The raw value is assigned to the enumeration case when it’s defined.

Here is an example of an enumeration with raw values of integers:

enum Direction: Int {
  case north = 1
  case south = 2
  case east = 3
  case west = 4
}

In this example, the enumeration Direction is of type Int and the cases are assigned raw values of 1, 2, 3, and 4.

You can also use the rawValue property to access the raw value of an enumeration case:

let southDirection = Direction.south
print(southDirection.rawValue) // 2

You can also initialize an enumeration case from its raw value using the init?(rawValue:) initializer:

if let direction = Direction(rawValue: 3) {
  print(direction) // Direction.east
}

Note that this initializer returns an optional, becuase it’s possible that the rawValue that you pass in may not exist in the enum.

© 2024 Kodeco Inc.