DEV Community

Theo Millard
Theo Millard

Posted on

Swift Basics: Enums

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Basic Enum Example

enum CompassPoint { case north case south case east case west } // Initiation can be done like this let currentState = CompassPoint.east // or like this let direction:CompassPoint = .east 
Enter fullscreen mode Exit fullscreen mode

Switch in Enum

switch directionToHead { case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") } 
Enter fullscreen mode Exit fullscreen mode

Iterable Enum

Here, we can check the count and loop over the enums

enum Beverage: CaseIterable { case coffee, tea, juice } let numberOfChoices = Beverage.allCases.count print("\(numberOfChoices) beverages available") for beverage in Beverage.allCases { print(beverage) } 
Enter fullscreen mode Exit fullscreen mode

By using enums, the variable can easily checked and compared.

Other things about enums is, you can use it to specify the error type that you want to return

enum FileError: Error { case notFound case permissionDenied(reason: String) } func readFile(named name: String) throws { if name.isEmpty { throw FileError.notFound } if name == "secret.txt" { throw FileError.permissionDenied(reason: "User lacks read access") } print("File '\(name)' read successfully.") } do { try readFile(named: "TEXT.txt") } catch let error as FileError { switch error { case .notFound: print("Error: File not found.") case .permissionDenied(let reason): print("Error: Permission denied - \(reason)") } } catch { print("An unknown error occurred: \(error)") } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)