使用 int 值将枚举编码为字符串
Posted
技术标签:
【中文标题】使用 int 值将枚举编码为字符串【英文标题】:Encoding enum with int values as String 【发布时间】:2022-01-17 02:27:44 【问题描述】:我正在使用 Flutter 为 android 和 ios 开发一个使用蓝牙的应用程序。 Android 和 Flutter 部分已经在运行,iOS 只剩下一小部分。目前我在将蓝牙属性发送到 Flutter 平台时遇到问题。我正在阅读它们,使用 int 值枚举来存储它们并使用 Json 对它们进行编码以将它们发送到 EventChannel。我的问题是我想以字符串形式发送它们,例如,如果属性如下:PROPERTY_WRITE = 8,它应该在 Json 中编码为“PROPERTY_WRITE”。你可以在下面看到我的代码:
enum BLEProperty: UInt, Codable
case PROPERTY_BROADCAST = 1
case PROPERTY_EXTENDED_PROPS = 128
case PROPERTY_INDICATE = 32
case PROPERTY_NOTIFY = 16
case PROPERTY_READ = 2
case PROPERTY_SIGNED_WRITE = 64
case PROPERTY_WRITE = 8
case PROPERTY_WRITE_NO_RESPONSE = 4
extension BLEProperty
private enum CodingKeys: String, CodingKey
case PROPERTY_BROADCAST
case PROPERTY_EXTENDED_PROPS
case PROPERTY_INDICATE
case PROPERTY_NOTIFY
case PROPERTY_READ
case PROPERTY_SIGNED_WRITE
case PROPERTY_WRITE
case PROPERTY_WRITE_NO_RESPONSE
func encode(to encoder: Encoder) throws
var container = encoder.container(keyedBy: CodingKeys.self)
switch self
case .PROPERTY_BROADCAST:
try container.encode(BLEProperty.PROPERTY_BROADCAST, forKey: .PROPERTY_BROADCAST)
case .PROPERTY_EXTENDED_PROPS:
try container.encode(BLEProperty.PROPERTY_EXTENDED_PROPS, forKey: .PROPERTY_EXTENDED_PROPS)
case .PROPERTY_INDICATE:
try container.encode(BLEProperty.PROPERTY_INDICATE, forKey: .PROPERTY_INDICATE)
case .PROPERTY_NOTIFY:
try container.encode(BLEProperty.PROPERTY_NOTIFY, forKey: .PROPERTY_NOTIFY)
case .PROPERTY_READ:
try container.encode(BLEProperty.PROPERTY_READ, forKey: .PROPERTY_READ)
case .PROPERTY_SIGNED_WRITE:
try container.encode(BLEProperty.PROPERTY_SIGNED_WRITE, forKey: .PROPERTY_SIGNED_WRITE)
case .PROPERTY_WRITE:
try container.encode(BLEProperty.PROPERTY_WRITE, forKey: .PROPERTY_WRITE)
case .PROPERTY_WRITE_NO_RESPONSE:
try container.encode(BLEProperty.PROPERTY_WRITE_NO_RESPONSE, forKey: .PROPERTY_WRITE_NO_RESPONSE)
【问题讨论】:
【参考方案1】:您可以添加一个返回枚举案例名称的计算属性,然后encode(to:)
函数变得更加简单
extension BLEProperty
var propertyName: String
"\(self)"
func encode(to encoder: Encoder) throws
var container = encoder.singleValueContainer()
try container.encode(self.propertyName)
例子
let properties: [BLEProperty] = [.PROPERTY_READ, .PROPERTY_BROADCAST]
do
let data = try JSONEncoder().encode(properties)
if let string = String(data: data, encoding: .utf8) print(string)
catch
print(error)
["PROPERTY_READ","PROPERTY_BROADCAST"]
【讨论】:
谢谢 Joakim,这是完美的解决方案!以上是关于使用 int 值将枚举编码为字符串的主要内容,如果未能解决你的问题,请参考以下文章