Simplifying with Associated Enums in Swift

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!

要查看或添加评论,请登录

Chanakya Hirpara的更多文章

  • Proxy Design Pattern in Swift

    Proxy Design Pattern in Swift

    The Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to…

  • Semaphores in Swift

    Semaphores in Swift

    Semaphores are essential tools for managing concurrency in Swift, helping you control access to resources and…

  • Grammar Agreement in Swift

    Grammar Agreement in Swift

    Swift provides a powerful feature to handle grammar agreement automatically using localized attributed strings. This…

  • Property Wrappers in Swift

    Property Wrappers in Swift

    Swift’s property wrappers are a powerful feature introduced to simplify and encapsulate property management logic. They…

  • ?? Attention Fiverr Software Developers: Beware of New Scam! ??

    ?? Attention Fiverr Software Developers: Beware of New Scam! ??

    Hello Fiverr family, I hope you're all thriving and successfully completing your gigs! I wanted to share an important…

    1 条评论
  • withCheckedThrowingContinuation in Swift

    withCheckedThrowingContinuation in Swift

    Swift’s concurrency model includes various tools to handle asynchronous operations more efficiently and intuitively…

  • The async Keyword in Swift

    The async Keyword in Swift

    The keyword in Swift helps you write code that performs tasks in the background without freezing your app's interface…

  • The @escaping Keyword in Swift

    The @escaping Keyword in Swift

    In Swift, closures are blocks of code that you can pass around and execute later. Sometimes, these closures need to be…

  • "indirect" Keyword in Swift

    "indirect" Keyword in Swift

    In Swift, the keyword is used to create data structures that reference themselves, like linked lists or trees. These…

  • Failable Initializers in Swift

    Failable Initializers in Swift

    A failable initializer in Swift is an initializer that can return if the initialization process fails. This is…

社区洞察

其他会员也浏览了