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

lea*_*him 6 enums ios swift

使用 Xcode 9.4.1 和 Swift 4.1

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

public enum TestEnum : UInt16{
case ONE    = 0x6E71
case TWO    = 0x0002
case THREE  = 0x0000
}
Run Code Online (Sandbox Code Playgroud)

我通过 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*/
Run Code Online (Sandbox Code Playgroud)

现在我还想在十六进制值后打印“ONE”。

我知道这个问题:如何在 Swift 中获取枚举值的名称? 但这是不同的,因为我想通过案例原始值而不是枚举值本身来确定案例名称。

期望输出:

命令类型 = 0x6E71,一

Ash*_*lls 8

您无法获得案例名称,因为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
Run Code Online (Sandbox Code Playgroud)


OOP*_*Per 6

您可以从它的 rawValue 创建一个枚举值,并使用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("---")
}
Run Code Online (Sandbox Code Playgroud)