代码之家  ›  专栏  ›  技术社区  ›  leachim

如何在swift4中通过枚举实例的原始值获取其名称?

  •  1
  • leachim  · 技术社区  · 8 年前

    使用Xcode 9.4.1和Swift 4.1

    对于Int类型中有多个事例的枚举,如何按其原始值打印事例名称?

    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*/
    

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

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

    期望输出:

    2 回复  |  直到 8 年前
        1
  •  7
  •   Ashley Mills    8 年前

    你不能把案子的名字 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
  •  6
  •   OOPer    8 年前

    可以从枚举值创建枚举值,并使用 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("---")
    }