Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get associated value in enums without switch

Tags:

ios

swift

I have enum:

enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)
}

MSRetailDemandRealm and MSRetailDemandRealm are both implement same protocol, that have variables title and stats. I want to extract this values, but i don't care of which object actually stored in. Consider following:

 switch data! {
        case .salesReturn(let object):
            titleString = object.title
            statistics = object.stats
        case .demand(let object):
            titleString = object.title
            statistics = object.stats
          break
        }

I have to go in each enum value to get property of protocol. Is any way i can do it shorter and cleaner? Get associated value, no matter what it is, as long as it conforms to my protocol, and get protocol values? Thanks.

like image 597
Evgeniy Kleban Avatar asked Dec 05 '17 17:12

Evgeniy Kleban


People also ask

What is associated value in enum Swift?

In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.

Why Swift enums with associated values Cannot have a raw value?

The Problem with Associated Values We had to do this because Swift doesn't allow us to have both: raw values and associated values within the same enum. A Swift enum can either have raw values or associated values.

What is raw value and associated value Swift?

The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so.

What is associated value?

The association value of a stimulus is a measure of its meaningfulness. It is a strong predictor of how easy it is to learn new information about that stimulus, for example to learn to associate it with a second stimulus, or to recall or recognize it in a memory test.


1 Answers

You could add a property to your enum that returns the protocol. For example:

enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)

    var realm: MSRetailRealm {
        switch self {
        case .salesReturn(let realm):
            return realm
        case .demand(let realm):
            return realm
        }
    }
}

Then, when you want to access those properties on a specific value of the enum, just use:

let operation = RetailDemandReturnOperation.salesReturn(value: MSRetailSalesReturnRealm())
let title = operation.realm.title
like image 108
dalton_c Avatar answered Oct 22 '22 22:10

dalton_c