Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Declare Enumerations in Swift
Written by Team Kodeco

An enumeration, or enum, is a data type that consists of a set of related values. These values are called “cases” and are defined within the enumeration. In Swift, enumerations can be defined using the enum keyword followed by the enumeration’s name and a set of cases.

Here’s an example of declaring an enumeration called Direction with four cases north, south, east and west:

enum Direction {
  case north
  case south
  case east
  case west
}

You can create a variable of the enumeration type and assign it a case.

var currentDirection = Direction.north

As a shortcut, you can use type inference as follows:

var newDirection: Direction = .east
newDirection = .west

Note that since the compiler knows that newDirection is of type Direction, you can use .east and .west rather than Direction.east and Direction.west.

In swift it also possible to create an enumeration case with associated values:

enum Barcode {
  case upc(Int, Int, Int, Int)
  case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

Note that the cases of an enumeration are not strings or integers, but are actual instances of the enumeration type. This means that enumeration cases can be compared using the equality operator (==) and can be used in switch statements and other control flow constructs.

© 2024 Kodeco Inc.