[英]How to get the name of an enumeration case by its raw value in Swift 4?
拥有类型为Int的多个案例的枚举时,如何通过其rawValue打印案例名称?
public enum TestEnum : UInt16{
case ONE = 0x6E71
case TWO = 0x0002
case THREE = 0x0000
}
我通过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*/
现在,我还想在十六进制值之后打印“ ONE”。
我知道一个问题: 如何在Swift中获取枚举值的名称? 但这有所不同,因为我想通过案例原始值而不是枚举值本身来确定案例名称。
所需输出:
命令类型= 0x6E71,一
由于枚举类型不是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
您可以从其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.