'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:
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)") } }
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) }
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.