How to get Enum rawValue based on its attribute value - Swift

This is my listing:

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 if there is a way to return rawValueif I provide a handle value?

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

How can i achieve this?

+4
source share
3 answers

You can create an initializer for your enumeration that takes a descriptor and returns an enumeration value for it, and 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

+4
source

, . , , ?

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

, , , .

, , House1 0, "Cottage", , . , , , , . , :

["Cottage", "House"]

0 "Cottage" (.. ).

+1
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
0
source

Source: https://habr.com/ru/post/1659609/


All Articles