我想对现有的NWInterface
类的实例进行编码,它有一个类型为NWInterface.InterfaceType
的type
字段,即enum
.
有什么方法可以轻松地将Encodable
接口添加到该嵌套类型中吗?目前,我的解决方法是在包含类的扩展中处理编码:
extension NWInterface : Encodable {
enum CodingKeys: CodingKey {
case name
case type
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
switch type {
case .wifi:
try container.encode("wifi", forKey: .type)
case .cellular:
try container.encode("cellular", forKey: .type)
case .wiredEthernet:
try container.encode("ethernet", forKey: .type)
case .loopback:
try container.encode("loopback", forKey: .type)
case .other:
try container.encode("other", forKey: .type)
default:
try container.encode("unknown", forKey: .type)
}
}
}
这感觉像是unsatisfactory,特别是对于我自己定义的enum
个类型,我可以简单地在定义时添加Encodable
接口,并"免费"获得实现.