ProgrammingiOS/Swift Developer

What is 'enum with associated values' in Swift and when should this construct be used instead of classes or structs?

Pass interviews with Hintsage AI assistant

Answer.

'Enums with associated values' in Swift allow each case to hold individual values (of different types). Such an enum effectively becomes an Algebraic Data Type, which is perfect for expressing a finite set of options with different additional data.

Use this construct:

  • For modeling states (e.g., loading states, operation results: success/error, etc.)
  • When a case requires additional parameters that differ in type
  • For type-safe patterns and reducing switch-case branches

Code example:

enum NetworkResult { case success(data: Data) case failure(error: Error) } func handle(result: NetworkResult) { switch result { case .success(let data): print("Data received: \(data)") case .failure(let error): print("Error: \(error.localizedDescription)") } }

Trick question.

Can you create an enum within an enum (nested enums), and why might this be necessary?

Answer: Yes, Swift supports nested enums. This is convenient for modeling nested states and ensuring scope. For example:

enum PaymentStatus { enum ErrorType { case declined, timeout } case success(amount: Double) case failure(type: ErrorType) }

Examples of real mistakes due to a lack of understanding of the nuances of the topic.


Story

In a project, a complex state model for a request was implemented using an enum with associated values; however, when new cases were added to the switch, the default handling was not implemented. This led to silent errors that were difficult to catch at runtime, rather than at compile time.


Story

A developer attempted to serialize an enum with associated values directly to JSON. Without manual Codable support for each case, the application lost data during decoding, causing critical bugs during synchronization with the server.


Story

In the networking layer, errors were transmitted using only classes, not enums. As a result, the list of errors quickly grew, with duplicate types and increased maintenance complexity, unlike with an enum solution, where the list of errors would be type-safe and centralized.