簡體   English   中英

如何在Swift 4中通過原始值獲取枚舉用例的名稱?

[英]How to get the name of an enumeration case by its raw value in 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訪問Enum:

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 ,因此您無法獲得與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

您可以從其rawValue創建一個枚舉值,並使用String.init(describing:) describing String.init(describing:)獲得其大小寫String。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM