ios - 如何通过 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,一
解决方案
你不能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
推荐阅读
- swift - 在没有 FileManager 的情况下将 UIDocument 保存到新 URL 时如何防止文件名冲突
- reactjs - 在 useEffect 中反应 setInterval
- algorithm - 根据内核扩展 CPU 小时数
- solidity - 当您将合约存储在映射中时,实际存储了什么?
- python - pygame 中有多个动画?
- javascript - 如何删除 JS var 中的空格?
- asp.net-core - 如何使用 NSubstitute 和 XUnit 模拟返回 bool 的 UpdateOneAsync 方法?
- django - 为什么我的表值没有显示在 django 模板中?
- python - 如何从句子中只提取单词?
- angular - Ionic 5/angular 不能再访问页面了?