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



使用 Xcode 9.4.1 和 Swift 4.1

有一个包含来自 Int 类型的多个案例的枚举,如何通过其 rawValue 打印案例名称?

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

我正在通过原始值访问枚举:

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

您无法获得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

最新更新