简体   繁体   English

如何在Swift 4中通过原始值获取枚举用例的名称?

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

Using Xcode 9.4.1 and Swift 4.1 使用Xcode 9.4.1和Swift 4.1

Having an enumeration with multiple cases from type Int, how can I print the case name by its rawValue? 拥有类型为Int的多个案例的枚举时,如何通过其rawValue打印案例名称?

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

I am accessing the Enum by the rawValue: 我通过rawValue访问Enum:

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. 现在,我还想在十六进制值之后打印“ ONE”。

I am aware of the Question: How to get the name of enumeration value in Swift? 我知道一个问题: 如何在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 命令类型= 0x6E71,一

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… 由于枚举类型不是String ,因此您无法获得与String一样的案例名称,因此您需要添加一个方法以自己返回它…

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

You can create an enum value from its rawValue and get its case String using String.init(describing:) . 您可以从其rawValue创建一个枚举值,并使用String.init(describing:) describing String.init(describing:)获得其大小写String。

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("---")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM