如何在Swift 4中通过原始值获取枚举用例的名称? [英] How to get the name of an enumeration case by its raw value in Swift 4?
问题描述
具有一个Int类型的多个案例的枚举,如何按其rawValue打印案例名称?
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
}
我正在通过rawValue访问枚举:
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*/
现在,我还想在十六进制值之后打印"ONE".
Now I additionally want to print "ONE" after the HEX value.
我知道以下问题:如何在Swift中获得枚举值的名称?但这有所不同,因为我想通过案例原始值而不是枚举值本身来确定案例名称.
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.
所需的输出:
命令类型= 0x6E71,一个
推荐答案
由于枚举类型不是 String
,因此您无法以 String
的形式获得案例名称,因此您需要添加一种自己返回的方法…
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
这篇关于如何在Swift 4中通过原始值获取枚举用例的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!