Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of an enumeration case by its raw value in Swift 4?

Tags:

enums

ios

swift

Using Xcode 9.4.1 and Swift 4.1

Having an enumeration with multiple cases from type Int, how can I print the case name by its rawValue?

public enum TestEnum : UInt16{
case ONE    = 0x6E71
case TWO    = 0x0002
case THREE  = 0x0000
}

I am accessing the Enum by the rawValue:

print("\nCommand Type = 0x" + String(format:"%02X", someObject.getTestEnum.rawValue))
/*this prints: Command Type = 0x6E71
if the given Integer value from someObject.TestEnum is 28273*/

Now I additionally want to print "ONE" after the HEX value.

I am aware of the Question: How to get the name of enumeration value in Swift? but this is something different because I want to determine the case name by the cases raw value instead of the enumeration value by itself.

Desired Output:

Command Type = 0x6E71, ONE

like image 922
leachim Avatar asked Aug 29 '18 11:08

leachim


People also ask

What is raw value or associated value in enum in 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.

How do you name an enum in Swift?

The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized. The values declared in an enum — up , down , left and right — are referred to as enumeration case. We use the case keyword to introduce a new enumeration case.

How do you find the enumeration value?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What is the raw underlying type of this enum?

What is raw underlying type of enum? Enum with Raw Values Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.


1 Answers

You can't get the case name as as String as the enum's type isn't String, so you'll need to add a method to return it yourself…

public enum TestEnum: UInt16, CustomStringConvertible {
    case ONE = 0x6E71
    case TWO = 0x0002
    case THREE = 0x0000

    public var description: String {
        let value = String(format:"%02X", rawValue)
        return "Command Type = 0x" + value + ", \(name)"
    }

    private var name: String {
        switch self {
        case .ONE: return "ONE"
        case .TWO: return "TWO"
        case .THREE: return "THREE"
        }
    }
}

print(TestEnum.ONE)

// Command Type = 0x6E71, ONE
like image 178
Ashley Mills Avatar answered Oct 13 '22 01:10

Ashley Mills