SteBra
SteBra

Reputation: 4247

How to get Enum's rawValue based on it's attribute value - Swift

This is my Enum:

enum Object: Int{

    case House1 = 0
    case House2 = 1

    var descriptor:String{
        switch self{
        case .House1: return "Cottage"
        case .House2: return "House"
        }
    }
}

I want to know is there a way to get rawValue returned if I provide value of descriptor?

For example, I want to know Enum value if my String is "Cottage" (It should return 0)

How can I achieve this?

Upvotes: 5

Views: 2071

Answers (3)

matt
matt

Reputation: 535964

It sounds like you've designed your object incorrectly for your own needs. If that was the sort of thing you wanted to do, why didn't you make the raw value a string?

enum Object: String {
    case House1 = "Cottage"
    case House2 = "House"
}

Now what you're asking for just works, right out of the box.

If there is some other reason why you need House1 to correspond to both 0 and "Cottage", tell us what it is. But so far, from what you've said, it sounds like what you want is not an enum at all. Perhaps a simple array would have been better:

["Cottage", "House"]

That gives you direct two-way interchange between 0 and "Cottage" (i.e. the index number).

Upvotes: 2

Asdrubal
Asdrubal

Reputation: 2481

enum Object: Int{

    case House1 = 0
    case House2 = 1

    var description: String {
        return descriptor
    }

    var descriptor:String{
        switch self{
        case .House1: return "Cottage"
        case .House2: return "House"
        }
    }

    static func valueFor(string:String) -> Int{
        switch string{
        case "Cottage": return 0
        case "House": return 1
        default: return 2
        }
    }
}


let obj = Object.House1

print(obj.description)
print(obj.rawValue)
print(Object.valueFor(string: "Cottage")

//Output
Cottage
0
0

Upvotes: 0

Jacob King
Jacob King

Reputation: 6177

You can create an initialiser for your enum that takes the descriptor and returns the enum value for it, then just call enumValue.rawValue. See the following:

enum Object: Int{

    case House1 = 0
    case House2 = 1

    var descriptor:String{
        switch self{
        case .House1: return "Cottage"
        case .House2: return "House"
        }
    }

    init(descriptor: String) {
        switch descriptor {
            case "Cottage": self = .House1
            case "House": self = .House2
            default: self = .House1 // Default this to whatever you want
        }
    }
}

Now do something like let rawVal = Object(descriptor: "House").rawValue

Upvotes: 5

Related Questions