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

拈花ヽ惹草 提交于 2021-02-20 13:28:08

问题


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


回答1:


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



回答2:


You can create an enum value from its rawValue and get its case String using String.init(describing:).

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

let enumRawValue: UInt16 = 0x6E71

if let enumValue = TestEnum(rawValue: enumRawValue) {
    print(String(describing: enumValue)) //-> ONE
} else {
    print("---")
}


来源:https://stackoverflow.com/questions/52076798/how-to-get-the-name-of-an-enumeration-case-by-its-raw-value-in-swift-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!