首页 > 解决方案 > 如何通过 Swift 4 中的原始值获取枚举案例的名称?

问题描述

使用 Xcode 9.4.1 和 Swift 4.1

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

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

我通过 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*/

现在我还想在 HEX 值之后打印“ONE”。

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

期望的输出:

命令类型 = 0x6E71,一

标签: iosswiftenums

解决方案


你不能String像枚举的类型那样得到 case name String,所以你需要添加一个方法来自己返回它......</p>

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

推荐阅读