我无法正确解码我的Codable类型.我已经阅读了一些关于使用相关类型制作Codable枚举的教程.我搜索过拼写错误,名称不匹配,或其他什么,但我无法发现任何错误.然而,每当我尝试对这些结构进行解码时(一个图层…这在扩展中的一个图层上定义了一个“属性”……但是图层的所有其他预定义部分都被正确地加/解码),我点击了解码(来自解码器:)方法中的“未找到密钥”异常.
extension Layer { struct Attribute: Codable { enum Value: Codable { case pulse(Double) case flash(Double) case draw(Double) private enum CodingKeys: String,CodingKey { case pulse,flash,draw } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .pulse(let value): try container.encode(value,forKey: .pulse) case .flash(let value): try container.encode(value,forKey: .flash) case .draw(let value): try container.encode(value,forKey: .draw) } } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) do { let value = try values.decode(Double.self,forKey: .pulse) self = .pulse(value) } catch (let error) { print(error) } do { let value = try values.decode(Double.self,forKey: .draw) self = .draw(value) } catch (let error) { print(error) } do { let value = try values.decode(Double.self,forKey: .flash) self = .flash(value) } catch (let error) { print(error) } self = .draw(0.0) } } var value: Value init(value: Value) { self.value = value } } }
我认为在解码之前,你应首先检查解码器容器中是否存在密钥.目前,你这样做:
原文链接:https://www.f2er.com/swift/319056.htmldo { let value = try values.decode(Double.self,forKey: .pulse) self = .pulse(value) } catch (let error) { print(error) } do { let value = try values.decode(Double.self,forKey: .draw) self = .draw(value) } catch (let error) { print(error) } do { let value = try values.decode(Double.self,forKey: .flash) self = .flash(value) } catch (let error) { print(error) }
解码器容器无法在那里拥有所有三个键,不是吗?
所以,解码前检查:
if values.contains(.pulse) { do { let value = try values.decode(Double.self,forKey: .pulse) self = .pulse(value) return // remember to return here,so you don't set self back to .draw(0.0) again! } catch (let error) { print(error) } } else if values.contains(.draw) { do { let value = try values.decode(Double.self,forKey: .draw) self = .draw(value) return } catch (let error) { print(error) } } else if values.contains(.flash) { do { let value = try values.decode(Double.self,forKey: .flash) self = .flash(value) return } catch (let error) { print(error) } }