【问题标题】:How to get the name of an enumeration case by its raw value in Swift 4?如何通过 Swift 4 中的原始值获取枚举案例的名称?
【发布时间】:2019-02-04 04:54:38
【问题描述】:

使用 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”。

我知道这个问题:How to get the name of enumeration value in Swift? 但这是不同的,因为我想通过案例原始值而不是枚举值本身来确定案例名称。

期望的输出:

命令类型 = 0x6E71, ONE

【问题讨论】:

标签: ios swift enums


【解决方案1】:

由于枚举的类型不是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

【讨论】:

    【解决方案2】:

    您可以从其 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("---")
    }
    

    【讨论】:

    • 完美解决方案!
    • 绝妙的答案!尝试使用 CaseIterable 和 Mirror,但没有运气。这成功了!!!
    • 好吧,我发现了一个边缘案例。如果枚举采用“CodingKey”,它将不起作用:-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2014-07-29
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多