Simplifying with Associated Enums in Swift
Associated enums in Swift are a nifty feature that let you attach values to each case. This adds flexibility, making enums a powerful tool in your coding toolkit.
How to Declare an Associated Enum
Here's a quick example:
enum Transportation {
case car(licensePlate: String)
case bicycle(brand: String, gearCount: Int)
case airplane(model: String, passengerCapacity: Int)
}
Using Associated Values
Create instances and access their values like this:
let myCar = Transportation.car(licensePlate: "XYZ 1234")
let myBike = Transportation.bicycle(brand: "Giant", gearCount: 21)
let myPlane = Transportation.airplane(model: "Boeing 747", passengerCapacity: 524)
Pattern Matching
Extract values using a switch statement:
func describeTransportation(_ transport: Transportation) {
switch transport {
case .car(let licensePlate):
print("Car with license plate: \(licensePlate)")
case .bicycle(let brand, let gearCount):
print("Bicycle: \(brand) with \(gearCount) gears")
case .airplane(let model, let capacity):
print("Airplane model \(model) with \(capacity) seats")
}
}
describeTransportation(myCar)
describeTransportation(myBike)
describeTransportation(myPlane)
Practical Use Case
Handling network responses can be streamlined with associated enums:
enum NetworkResponse {
case success(data: Data)
case failure(error: Error)
case loading
}
func handleResponse(_ response: NetworkResponse) {
switch response {
case .success(let data):
print("Data received: \(data)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
case .loading:
print("Loading...")
}
}
handleResponse(.loading)
handleResponse(.success(data: Data()))
handleResponse(.failure(error: NSError(domain: "NetworkError", code: 404, userInfo: nil)))
Associated enums make your code cleaner and more expressive. Give them a try in your next project!