BudiBadu Logo
Samplebadu

Swift by Example: Enums

Swift 5.x

Master Swift enumerations with this sample code showing enum case declarations, type inference with dot syntax, powerful associated values for storing different data types per case, and exhaustive pattern matching with switch statements.

Code

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

var direction = CompassPoint.north
direction = .east // Type is known, can omit Enum name

// Enums with Associated Values
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var product = Barcode.upc(8, 85909, 51226, 3)
product = .qrCode("ABCDEFGHIJKLMNOP")

switch product {
case .upc(let numberSystem, let manufacturer, let product, let check):
    print("UPC: (numberSystem), (manufacturer), (product), (check).")
case .qrCode(let productCode):
    print("QR code: (productCode).")
}

Explanation

Enumerations (enums) define a common type for a group of related values. Swift enums are much more powerful than in C or Objective-C. They don't have to be integers; they can be first-class types in their own right. They can even have methods and computed properties.

One powerful feature is Associated Values. Each case in an enum can store different types of data. For example, a Barcode enum can store 4 integers for a UPC or a String for a QR code. This allows for creating discriminated unions or variant types.

You typically use a switch statement to match against enum values. Swift's switch must be exhaustive, meaning it must cover every case. When matching associated values, you can extract the values using let or var directly in the case statement.

Code Breakdown

2-5
case north, south, east, west defines the enum cases.
9
.east is shorthand for CompassPoint.east when type is inferred.
13
case upc(Int, Int, Int, Int) defines a case with associated tuple values.
21
case .upc(let numberSystem, ...) extracts associated values in pattern matching.